TypeError: Cannot read property 'setState' of undefined in ReactJs

Dung Do Tien Jul 19 2021 284

I have a small project with ReactJs. I have created a form to help increment count numbers when clicking on a button. It looks like below:

import React from 'react';
import './App.css';

class App extends React.Component 
{
    constructor(props)
    {
        super(props);
        //defining state
        this.state={countTime:1};
    }

    updateCount()
    {
        //updating the time by set state
        this.setState( (state,props) =>  {countTime:countTime + 1}  );
    }

    render()
    {
        return (
            <div>
                <h2>Count right now is {this.state.countTime}</h2>
                <button onClick={this.updateCount}>Update Count</button>
        
            </div>
        );
    }
}
export default App;

After running the project, I get an error TypeError: Cannot read property 'setState' of undefined.

TypeError: Cannot read property 'setState' of undefined

I knew that this.setState() command throw an exception because this keyword was null.

How can I fix it?

Have 3 answer(s) found.
  • d

    dang nhat hai long Jul 19 2021

    you can use the arrow function to avoid binding things. Here is the example:

    constructor(props) {
    super(props);
      state = {};
    }
    
    updateCount = () => {
      // your function here
    }

    And it works for me!!

  • D

    Deepansh Yadav Jul 19 2021

    The issue occurs because the this keyword is not pointing out the right scope of the component. You can fix this by binding your function:

    constructor(props) {
    super(props);
      state = {};
      
      this.updateCount = this.updateCount.bind(this);
    }
    
    updateCount() {
      // your function here
    }

    I hope it usefull for you!

  • h

    hiep nguyenduc Jul 19 2021

    You need to bind countTime

    constructor(props) {
       ...
       this.updateCount = this.updateCount.bind(this)
    }

    or use the arrow function

    updateCount = () => {
        //updating the time by set state
        this.setState( (state,props) =>  {countTime: countTime + 1}  );
    }

    and change your setState to

    this.setState({
      countTime: countTime + 1
    });

    or

    this.setState( (state,props) =>  ({countTime: countTime + 1}));

    I hope it helpful for you.

Leave An Answer
* NOTE: You need Login before leave an answer

* Type maximum 2000 characters.

* All comments have to wait approved before display.

* Please polite comment and respect questions and answers of others.

Popular Tips

X Close