【问题标题】:Unhandled Rejection (TypeError): Cannot read property 'setState' of undefined未处理的拒绝(TypeError):无法读取未定义的属性“setState”
【发布时间】:2019-06-03 05:58:58
【问题描述】:

我知道对此有很多答案,例如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


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2021-11-15
      • 2019-04-07
      • 2021-03-04
      • 2019-07-19
      • 2020-04-09
      • 2019-11-13
      • 2021-10-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多