HiveBrain v1.2.0
Get Started
← Back to all entries
debugjavascriptreactCritical

React - uncaught TypeError: Cannot read property 'setState' of undefined

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
setstateundefineduncaughtcannotreacttypeerrorreadproperty

Problem

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 (
            
                {this.state.count}
                +
            
        );
    }
}

Solution

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

Code Snippets

constructor(props) {
    super(props);

    this.state = {
        count : 1
    };

    this.delta = this.delta.bind(this);
}
constructor(props) {
    super(props);

    this.state = {
        count : 1
    };

}

delta = ()=> {
    this.setState({
        count : this.state.count++
    });
}

Context

Stack Overflow Q#32317154, score: 604

Revisions (0)

No revisions yet.