未处理的拒绝(TypeError):无法读取未定义的属性“ setState”

时间:2019-01-08 14:07:27

标签: reactjs

我知道有很多答案,例如this one。我确实在组件构造函数中添加了.bind(this)。我也尝试了粗箭头方法(fakeApiCall = ()=>{ ... }),但是当我单击Change Me时,此错误仍然显示:

enter image description here

import React, { Component } from 'react';
import axios from 'axios';
class App extends Component {

  constructor(props){
    super(props);
    this.state = {
      count : 1000
    };
    this.fakeApiCall = this.fakeApiCall.bind(this);

  }

  fakeApiCall (){
    axios.get('https://jsonplaceholder.typicode.com/users')
    .then(function(response){
    // the response comes back here successfully
      const newCount = response.data.length;
    // fail at this step
      this.setState({ count : Math.floor(newCount) });
    });
  }

  render() {
    return (
      <div className="App">
        <span style={{ fontSize : 66 }}>{this.state.count}</span>
        <input type='button' onClick={this.fakeApiCall} value='Change me' />
      </div>
    );
  }
}

export default App;

1 个答案:

答案 0 :(得分:2)

您的fakeApiCall函数已绑定到您的上下文,但axios中的函数回调未绑定。

要解决此问题,您可以使用箭头功能,因为它们会自动与您的班级绑定。您也可以为fakeApiCall进行操作并删除其绑定:

class App extends Component {
    constructor(props) {
        super(props);
        this.state = {
            count: 1000
        };
    }

    fakeApiCall = () => {
        axios.get('https://jsonplaceholder.typicode.com/users')
            .then(response => { //This is an arrow function
                const newCount = response.data.length;
                this.setState({ count: Math.floor(newCount) });
            });
    }

    render() {
        return (
            <div className="App">
                <span style={{ fontSize: 66 }}>{this.state.count}</span>
                <input type='button' onClick={this.fakeApiCall} value='Change me' />
            </div>
        );
    }
}