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

后端 未结 18 2337
清歌不尽
清歌不尽 2020-11-22 13:35

I am getting the following error

Uncaught TypeError: Cannot read property \'setState\' of undefined

even after binding delta in

相关标签:
18条回答
  • 2020-11-22 14:18

    When using ES6 code in React always use arrow functions, because the this context is automatically binded with it

    Use this:

    (videos) => {
        this.setState({ videos: videos });
        console.log(this.state.videos);
    };
    

    instead of:

    function(videos) {
        this.setState({ videos: videos });
        console.log(this.state.videos);
    };
    
    0 讨论(0)
  • 2020-11-22 14:18

    You need to bind this to the constructor and remember that changes to constructor needs restarting the server. Or else, you will end with the same error.

    0 讨论(0)
  • 2020-11-22 14:19

    In ES7+ (ES2016) you can use the experimental function bind syntax operator :: to bind. It is a syntactic sugar and will do the same as Davin Tryon's answer.

    You can then rewrite this.delta = this.delta.bind(this); to this.delta = ::this.delta;


    For ES6+ (ES2015) you can also use the ES6+ arrow function (=>) to be able to use this.

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

    Why ? From the Mozilla doc :

    Until arrow functions, every new function defined its own this value [...]. This proved to be annoying with an object-oriented style of programming.

    Arrow functions capture the this value of the enclosing context [...]

    0 讨论(0)
  • 2020-11-22 14:19

    Just change your bind statement from what you have to => this.delta = this.delta.bind(this);

    0 讨论(0)
  • 2020-11-22 14:20

    Arrow function could have make your life more easier to avoid binding this keyword. Like so:

     delta = () => {
           this.setState({
               count : this.state.count++
          });
       }
    
    0 讨论(0)
  • 2020-11-22 14:22

    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.

    0 讨论(0)
提交回复
热议问题