You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用axios请求JSON端点时出现TypeError,已获数据仍报错如何解决?

解决React componentDidMount中axios回调的TypeError问题

嘿,这个问题我太熟了!你遇到的TypeError根本原因是回调函数里的this指向不对——在普通function定义的then/catch回调里,this已经不再指向你的React组件实例了,所以调用this.setState自然会报错。

下面给你几个简单有效的解决办法:

方法一:用箭头函数替代普通函数(最推荐)

箭头函数不会绑定自己的this,它会继承外层作用域的this(也就是你的组件实例),完美解决指向问题。而且代码更简洁:

componentDidMount() {
  axios.get("https://web-code-test-xxx-games-prd.appspot.com/cards.json")
    .then((response) => {
      const easyResponse = response.data.levels[0]['difficulty']
      const easyCards = response.data.levels[0]['cards']
      // 顺便提一句:可以把两次setState合并成一次,减少不必要的重渲染
      this.setState({ 
        easy: easyResponse,
        easyCards: easyCards 
      })
    })
    .catch((error) => {
      console.log(error)
    })
}

方法二:提前保存组件的this引用

在回调函数外把组件的this存到一个变量(比如that/self)里,回调里用这个变量访问组件实例:

componentDidMount() {
  const that = this; // 保存组件的this引用
  axios.get("https://web-code-test-xxx-games-prd.appspot.com/cards.json")
    .then(function(response) {
      const easyResponse = response.data.levels[0]['difficulty']
      const easyCards = response.data.levels[0]['cards']
      that.setState({ easy: easyResponse })
      that.setState({ easyCards: easyCards })
    })
    .catch(function(error) {
      console.log(error)
    })
}

方法三:用bind绑定this

通过bind(this)给回调函数手动绑定组件的this,确保回调内部的this指向正确:

componentDidMount() {
  axios.get("https://web-code-test-xxx-games-prd.appspot.com/cards.json")
    .then(function(response) {
      const easyResponse = response.data.levels[0]['difficulty']
      const easyCards = response.data.levels[0]['cards']
      this.setState({ easy: easyResponse })
      this.setState({ easyCards: easyCards })
    }.bind(this)) // 绑定组件的this到回调
    .catch(function(error) {
      console.log(error)
    }.bind(this))
}

其中方法一是现在React开发里最常用的方案,不仅解决问题还让代码更清爽,优先推荐哦!

内容的提问来源于stack exchange,提问作者Kevin T.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:53:10