Dangling_pointer Dangling_pointer - 1 month ago 8
React JSX Question

Uncaught TypeError: Cannot read property 'setState' of undefined

I am getting

Uncaught TypeError: Cannot read property 'setState' of undefined
even after binding delta in the constructer.

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>
);
}
}

Answer

This is due to this.delta not being bound to this.

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.