【问题标题】:React state undefined in axios get request在 axios 获取请求中未定义的反应状态
【发布时间】:2019-06-05 16:01:36
【问题描述】:
state = {
    locationData: {}
  }

  componentDidMount() {
    axios.get('...')
      .then(res => {
        const data = res.data;

        parseString(data, function (err, result) {
          this.setState({locationData: result.data[0]}, function(){console.log(this.state.locationData);})
        });
      })
  }

给我错误:

Uncaught (in promise) TypeError: Cannot read property 'setState' of undefined

我发现我需要绑定,但在这种情况下我不明白如何绑定。

【问题讨论】:

  • 只需在parseString 的回调主体后附加.bind(this) 或使用箭头函数代替
  • 您能提供parseString 代码吗?
  • 那似乎没有任何作用...
  • 鉴于您的问题标题,我只想指出错误消息明确指出 this 未定义,而不是 setState 或“反应状态”;这应该让您知道function 中的this 不再是对您的组件实例的引用。并在此处搜索错误导致:

标签: javascript reactjs state


【解决方案1】:

如 cmets 中所述,您可以在函数体之后添加 .bind(this)。一般来说,我认为在回调函数上调用方法不是很可读所以我的建议是将你的回调切换为箭头函数,或者在外部定义回调并将其作为参数传递。

第一种方法

state = {
    locationData: {}
  }

  componentDidMount() {
    axios.get('...')
      .then(res => {
        const data = res.data;

        parseString(data, (err, result)=> {
          this.setState({locationData: result.data[0]}, function(){console.log(this.state.locationData);})
        });
      })
  }

第二种方法

state = {
    locationData: {}
  }

  componentDidMount() {

    axios.get('...')
      .then(res => {
        const data = res.data;
        const callback = function (err, result) {
          this.setState({locationData: result.data[0]}, function(){console.log(this.state.locationData);})
        }
        parseString(data, callback.bind(this));
      })
  }

【讨论】:

    【解决方案2】:

    问题是由于parseString 函数回调中的上下文丢失造成的。

    使用箭头函数:

    componentDidMount() {
        axios.get('...')
          .then(res => {
            const data = res.data;
    
            parseString(data, (err, result) => {
              this.setState({locationData: result.data[0]}, () => {console.log(this.state.locationData);})
            });
          })
      }
    

    或者绑定这个:

    componentDidMount() {
        axios.get('...')
          .then(res => {
            const data = res.data;
    
            parseString(data, (function (err, result) {
              this.setState({locationData: result.data[0]}, (function(){console.log(this.state.locationData);}).bind(this))
            }).bind(this));
          })
      }
    

    【讨论】:

      【解决方案3】:

      您可以将函数 (err, result){...} 更改为 (err, result) => {...} 因为箭头函数没有自己的这个属性。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-06-26
        • 2019-06-27
        • 2020-03-29
        • 2020-07-05
        • 1970-01-01
        • 2021-02-11
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多