Reactjs this.setState is not a function error

You need to bind this.showProfile in the component constructor

this.showProfile = this.showProfile.bind(this)

More detail about this on the Handling Events page of the React doc : https://facebook.github.io/react/docs/handling-events.html


Expanding on Delapouite's answer if you don't like to bind every function in the constructor you can use arrow functions to automatically bind to the correct context.

For example:

class AppBarLayout extends React.Component {
  constructor(props) {
      super(props);

      this.state = {
        visibleSideBar:true,
        slide:""
      }
  }

  // Now showProfile is an arrow function
  showProfile = () => {
    this.setState({
        slide:'slide'
    });
    console.log(this.state.slide);
  }

  render(){
    return(
      <div>
        <header>
          <NavBar show={this.showProfile}/>
          <Profile slide={this.state.slide}/>
        </header>
      </div>
    );
  }
}
export default AppBarLayout;

In my case, I solved the problem without binding.

Declaring the method like this was generating the error:

  async onSubmit(e) {
     event.preventDefault();
     this.setState({ shopEthereumAddress: e.target.id });
  }

The CORRECT declaration which will not generate the error is this:

onSubmit = async event => {
    event.preventDefault();
    this.setState({ shopEthereumAddress: event.target.id });
}

This works.

Tags:

Reactjs