Next.js中Axios请求报错:TypeError: Cannot read properties of undefined (reading 'status')
解决Next.js中Axios请求报错:TypeError: Cannot read properties of undefined (reading 'status')
问题原因
报错出现在catch块的let status = err.response.status;代码行——当请求未成功到达服务器(比如网络中断、跨域拦截、请求超时等场景)时,err.response会是undefined,直接读取其status属性就会抛出类型错误。
React项目中未报错只是因为运行时没触发这类无响应的错误场景,和框架本身无关,并非Next.js特有问题。
修复方案
修改catch块中获取status的逻辑,先判断err.response是否存在,再读取status属性,可选两种写法:
写法1:使用可选链操作符(ES2020+支持)
axios .request(options) .then(function (response) { console.log("res.data", response.data); const token = response.data.token; checkStatus(token); }) .catch((err) => { let error = err.response ? err.response.data : err; // 用可选链避免undefined读取属性报错 let status = err.response?.status; console.log("status", status); if (status === 429) { console.log("too many requests", status); showErrorToast( `当日请求配额100次已用完!请参考freeCodeCamp的教程搭建自己的RAPID API Judge0!`, 10000 ); } // 额外处理无response的情况 if (!status) { console.log("请求失败:网络错误或未连接到服务器"); showErrorToast("网络异常,请检查连接后重试", 3000); } setProcessing(false); console.log("catch block...", error); });
写法2:传统条件判断
axios .request(options) .then(function (response) { console.log("res.data", response.data); const token = response.data.token; checkStatus(token); }) .catch((err) => { let error = err.response ? err.response.data : err; let status = null; if (err.response) { status = err.response.status; } else { console.log("请求失败:网络错误或未连接到服务器"); showErrorToast("网络异常,请检查连接后重试", 3000); } console.log("status", status); if (status === 429) { console.log("too many requests", status); showErrorToast( `当日请求配额100次已用完!请参考freeCodeCamp的教程搭建自己的RAPID API Judge0!`, 10000 ); } setProcessing(false); console.log("catch block...", error); });
注意事项
- 可选链操作符
?.需要项目环境支持ES2020及以上,Next.js默认支持,无需额外配置。 - 建议补充无response场景的错误提示,提升用户体验。
内容的提问来源于stack exchange,提问作者user7200977
相关产品推荐
相关产品推荐

