Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot read property 'enqueueSetState' of undefined in ReactJS

I'm not quite sure why I'm getting this error.

class ContentProcessing extends Component {

    constructor(props) {
        super(props);

        this.state = {content: currentData};
        this.setData = this.setData.bind(this);
    }

    setData(data) {
        this.setState({
            content: data
        });
    }

    render() {
        return (
                <div>
                    <Card title={this.state.content} />
                </div>
        );
    }
}

The error is reported at

    this.setState({
        content: data
    });

Basically I'm launching setData from a Button in another class, as soon as I click it my page breaks and I receive the error.

I checked and it looks like in setData(), this.state is undefined so I suppose that's probably where the problem comes from.

I've looked at a few other answers that were having this same problem but their fixes don't seem to be working for me.

like image 632
Leonardo Petrucci Avatar asked Dec 07 '25 05:12

Leonardo Petrucci


1 Answers

This error is because this.setState in not bind to this in main class. If you want to pass setState to somewhere else you need to bind it first in its main class:

class ContentProcessing extends Component {

constructor(props) {
    super(props);

    this.state = {content: currentData};
    this.setData = this.setData.bind(this);
    this.setState = this.setState.bind(this); // <- try by adding this line
}}
like image 141
QauseenMZ Avatar answered Dec 08 '25 17:12

QauseenMZ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!