0

I have the following on line 163:

this.setState(data)

Then right below it I have this:

(function(data){
  setTimeout(() => {
    // do some stuff
  }, 5)
}).call(this, data)

When I comment out the latter, it all works fine. When I leave it there, for some reason I get an undefined error coming from line 163, saying this.setState is not a function.

Also when I simply replace the second snippet with

setTimeout(() => {
    // do stuff
  }, 5)

again, it works fine (except for the fact that sometimes the data variable isn't what it should be... not always though, weird).

How is this happening? How can code that hasn't been executed yet make this.setState undefined? I even checked in the debugger and this is set to what it should be right before it throws the error... am I missing something here?

jo_va
  • 13,504
  • 3
  • 23
  • 47
M. Farnik
  • 235
  • 1
  • 3
  • 9
  • _"I even checked in the debugger"_ - Begs the question: Why? Setting a breakpoing in the function body could answer your question... – kralyk Mar 10 '19 at 22:21
  • Kind of a shot in the dark here but you may want to consider passing a copy of your `data` rather than a reference into `setState` - a quick and dry approach would be doing `{ ...data }` – Wex Mar 10 '19 at 22:24

1 Answers1

2

The code in the second code block (an IIFE) is surrounded by parentheses. There is an unterminated statement before it. Hence, the JS interpreter will call the result of this.setState() which is not a function, resulting in an error.

Adding a semicolon at the end of this.setState() should solve it.

this.setState();

jro
  • 900
  • 1
  • 10
  • 21