Uncaught TypeError错误:无法读取undefined的'then'属性及Promise返回问题
问题分析与解决
错误根源
你遇到的"无法读取undefined的属性'then'",本质是props.saveProfile()没有返回Promise——准确说它返回的是undefined,自然没法链式调用.then()。
问题出在mapDispatchToProps的saveProfile方法里:你调用了dispatch(saveProfileThunkCreator(editDataAboutMe)),但没把dispatch的结果返回。Redux Thunk的特性是,dispatch一个thunk函数时,会返回这个thunk的执行结果(也就是你写的那个async函数的Promise)。但现在你的代码里,saveProfile只执行了dispatch动作,没把Promise传递出去,所以调用props.saveProfile()拿到的就是undefined。
修复方案
给mapDispatchToProps里的saveProfile加上return,把dispatch的结果返回即可:
mapDispatchToProps = (dispatch) => ({ saveProfile: (editDataAboutMe) => { // 新增return,将dispatch返回的Promise传递给调用者 return dispatch(saveProfileThunkCreator(editDataAboutMe)) } })
额外优化(非必须)
你的thunk函数里return await Promise.resolve()可以简化为return,因为async函数本身会自动把返回值包装成Promise,写await Promise.resolve()属于多余操作,不影响功能但不够简洁。
内容的提问来源于stack exchange,提问作者SeeYou1ater
相关产品推荐
相关产品推荐

