首页 > 解决方案 > 未处理的拒绝(TypeError):无法读取未定义的属性“setState”

问题描述

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

在此处输入图像描述

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;

标签: reactjs

解决方案


您的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>
        );
    }
}

推荐阅读