Why does my function call show this.setState as undefined?

Question

Why does my function call show this.setState as undefined?

Answer

Typically when you see an error message saying that a variable is undefined, it means that there is no value assigned to the variable you’re trying to access. If you encounter this error while trying to access a property of the this keyword in a class, then this is not defined and your function is being called out of scope.

In order to put your function in the scope of your class, then bind the function in your constructor.

class MyComponent extends React.Component {
   constructor(props) {
      ...
      this.fn = this.fn.bind(this);
   }

   fn() {
      this.setState(...)
   }
}

By doing this you can pass your function anywhere outside your class. When the function is called, it will have access to anything that is in the scope of your class.