React - uncaught TypeError: Cannot read property 'setState' of undefined
Full error message
I am getting the following error
Uncaught TypeError: Cannot read property 'setState' of undefined
even after binding delta in the constructor.
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = {
count : 1
};
this.delta.bind(this);
}
delta() {
this.setState({
count : this.state.count++
});
}
render() {
return (
<div>
<h1>{this.state.count}</h1>
<button onClick={this.delta}>+</button>
</div>
);
}
}Solutionsource: stackoverflow \u2197
This is due to this.delta not being bound to this. Option A: In order to bind set this.delta = this.delta.bind(this) in the constructor: constructor(props) { super(props); this.state = { count : 1 }; this.delta = this.delta.bind(this); } Currently, you are calling bind. But bind returns a bound function. You need to set the function to its bound value. Option B: Use an arrow function: constructor(props) { super(props); this.state = { count : 1 }; } delta = ()=> { this.setState({ count : this.state.count++ }); }
API access
Get this solution programmatically \u2014 free, no authentication.
curl https://depscope.dev/api/error/e0120e86055568cd6ca19d4d5f80c9374c87808b08d2c2eb937e68e6941698e3hash \u00b7 e0120e86055568cd6ca19d4d5f80c9374c87808b08d2c2eb937e68e6941698e3