【问题标题】:Unhandled rejection (Type Error): Cannot read property 'data' of undefined未处理的拒绝(类型错误):无法读取未定义的属性“数据”
【发布时间】:2021-10-30 14:26:46
【问题描述】:

我一直在尝试用react js开发一个应用,这个错误来了。

出现此错误的行是:

else{
 history.push({
         pathname:"/fullpage-error",
         state:{details:e.response.data.errors[0]}      //this is the main line of error
         });
}
}
};
export default globalAPIFunction;

【问题讨论】:

  • 似乎响应未定义。使用 console.log('response', e.response) 查看它的输出

标签: reactjs


【解决方案1】:

发生错误的那一行变量“e”的值是多少?

变量e没有“response”属性(它将是未定义的),因此无法访问未定义的“数据”属性。

如果变量 e 是您从 API 服务或任何第三方应用程序接收的动态变量,您可以在语句之前添加空指针检查

else{
if(e.response)
 history.push({
         pathname:"/fullpage-error",
         state:{details:e.response.data.errors[0]}      //this is the main line of error
         });
}
}
};
export default globalAPIFunction;

阅读更多关于 “类型错误”:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypeError

【讨论】:

    【解决方案2】:

    由于'e'对象尚未设置,因此引发错误。 您需要先检查它是否已定义或不这样做

    else{
     history.push({
             pathname:"/fullpage-error",
             state:{details:e.response ? e.response.data.errors[0] : ''}      //this is the main line of error
             });
    }
    }
    };
    export default globalAPIFunction;
    

    【讨论】:

      猜你喜欢
      • 2021-07-24
      • 1970-01-01
      • 2020-04-29
      • 2019-10-22
      • 1970-01-01
      • 2021-01-13
      • 1970-01-01
      • 1970-01-01
      • 2021-07-26
      相关资源
      最近更新 更多