将axios请求结果存入const并返回时遇response.data未定义错误求助
解决axios请求后无法获取response.data的问题
你的问题出在同时混用了await和.then()/.catch(),导致response变量的值并非axios返回的响应对象:
.then()里你只执行了console.log,这个函数的返回值是undefined,所以await拿到的就是undefined- 后续访问
response.data自然会触发undefined is not an object的错误
下面是两种修复方案,按需选择:
方案一:用try/catch替代then/catch(推荐,更符合async函数的写法逻辑)
export async function getCategories() { const https = "xxxxxx"; const url = `${https}/api/Category/GetCategories`; const userToken = "xxxxxxxx"; const authStr = "Bearer ".concat(userToken); const options = { method: "POST", headers: { Authorization: authStr, }, url: url, }; try { // 直接用await拿到完整的响应对象 const response = await axios(options); console.log(response.data[0].categoryName); const fetchedCategories = response.data[0]; console.log("🚀 ~ file: menu.js:27 ~ getCategories ~ fetchedCategories", fetchedCategories); return fetchedCategories; } catch (error) { console.log(error.toJSON()); // 可选:抛出错误让调用方处理,或者返回默认值(比如[]) throw error; } }
方案二:坚持用then/catch时,确保返回正确数据
如果不想用try/catch,就去掉await,直接返回axios的Promise链,同时在then里返回需要的数据:
export async function getCategories() { const https = "xxxxxx"; const url = `${https}/api/Category/GetCategories`; const userToken = "xxxxxxxx"; const authStr = "Bearer ".concat(userToken); const options = { method: "POST", headers: { Authorization: authStr, }, url: url, }; return axios(options) .then((response) => { console.log(response.data[0].categoryName); const fetchedCategories = response.data[0]; console.log("🚀 ~ file: menu.js:27 ~ getCategories ~ fetchedCategories", fetchedCategories); // 必须返回需要的数据,调用函数的地方才能拿到结果 return fetchedCategories; }) .catch((error) => { console.log(error.toJSON()); throw error; }); }
关键注意点
- 不要在async函数里同时混用
await和.then(),会混淆变量的实际返回值 - 错误处理要彻底,避免出现
Possible Unhandled Promise Rejection警告 - 无论哪种方案,都要确保最终返回你需要的数据,或者正确传递错误给调用方
内容的提问来源于stack exchange,提问作者Zakaria
相关产品推荐
相关产品推荐

