【问题标题】:Unhandled Rejection (TypeError): Cannot read property 'data' of undefined未处理的拒绝(TypeError):无法读取未定义的属性“数据”
【发布时间】:2019-05-20 09:59:18
【问题描述】:

它显示以下错误: 未处理的拒绝(TypeError):无法读取未定义的属性“数据”

        axios.get(`http://localhost:4000/api/AMS/country`)
     {
           .then(response => {
             //In the below line I am getting the error
             const country_Claim_Type = response.data;
             console.log(country_Claim_Type);
             this.setState({ country_Claim_Type });
                 })
       }

我期待一些 json 数据,但我在控制台中未定义。

【问题讨论】:

  • 那么当你 console.log() 输出响应时,它会显示/提供什么?
  • 它只显示“未定义”。我认为数据变得空,这就是为什么它显示未定义但我不知道为什么?
  • 错误信息表示未定义响应,可能是返回错误?
  • 是的,它抛出了以下错误:TypeError: Cannot read property 'data' of undefined
  • 我解决了这个问题,有一个愚蠢的错误,错误是我忘了把 return 放在 axios.get 之前

标签: reactjs api


【解决方案1】:

我认为你的代码结构不太正确:

axios.get(`http://localost:4000/api/AMS/country`)
// You had an erroneous { here
  .then(response => {
    // Your console.log() on response here should show 'data'
  }
);

【讨论】:

    【解决方案2】:

    由于发生了错误,它没有返回任何内容。在 axios.get 之前添加了一个 return 关键字。

     return axios.get(`http://localhost:4000/api/AMS/country`)
         {
               .then(response => {
                 //In the below line I am getting the error
                 const country_Claim_Type = response.data;
                 console.log(country_Claim_Type);
                 this.setState({ country_Claim_Type });
                     })
           }
    

    【讨论】:

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