Axios封装接口未返回Promise,触发Cannot read properties of undefined错误如何修复?
解决Axios接口调用函数无法使用
.then()的问题 问题的核心是你写的editPost函数没有返回Axios请求生成的Promise对象,导致调用editPost()后得到的是undefined,自然没法调用.then()方法。
修改editPost函数
只需要在函数里加上return,把Axios请求的结果返回出去就行:
export const editPost = (id, post) => { // 返回Axios请求的Promise对象 return api(`/posts/${id}`, { method: 'put', data: post }); };
为什么这样改?
Axios的请求调用(包括你用api.create()创建的实例调用)本身就会返回一个Promise对象,只要把这个Promise返回给调用者,就能正常使用.then()或者await来处理响应结果。
可选:用async/await优化调用代码
如果你觉得.then()的写法不够直观,也可以把调用函数改成async函数,用await处理:
const editThisPost = async (authorName, category, blogText) => { try { const res = await editPost(id, { authorName, category, blogText }); setPost(res); setEditing(false); } catch (error) { // 这里可以添加错误处理逻辑,比如提示用户编辑失败 console.error('编辑帖子出错:', error); } };
内容的提问来源于stack exchange,提问作者David Reke
相关产品推荐
相关产品推荐

