使用Async/Await与Redux-thunk时触发错误:Actions must be plain objects
解决Redux-Thunk中使用async/await出现的"Actions must be plain objects"错误
你这是踩了Redux-Thunk新手常见的坑啦!报错提示说得很清楚:Redux默认只认普通对象类型的action,要处理异步逻辑必须靠中间件,但你的写法没满足Thunk的要求。
问题根源
Redux-Thunk的核心是允许action creator返回一个函数(而不是普通对象),这个函数可以包含异步逻辑,还能拿到dispatch方法来发送真正的action。但如果你的action creator是async函数,它默认会返回一个Promise,而不是Thunk需要的函数,这就触发了错误。
修复步骤
首先确认你的Redux Store已经正确配置了Thunk中间件(这是基础!):
import { createStore, applyMiddleware } from 'redux'; import thunk from 'redux-thunk'; import rootReducer from './path/to/rootReducer'; const store = createStore( rootReducer, applyMiddleware(thunk) // 这行必须加上,不然Thunk没法工作 );
然后修改你的toggleTwitterAuthState函数,让它返回一个包含async/await逻辑的函数,在异步操作完成后用dispatch发送普通对象action:
export const toggleTwitterAuthState = (twitterIsCurrentlyLinked, contributorUserId) => { // 返回Thunk函数,接收dispatch作为参数 return async (dispatch) => { let actionType = ""; try { if (twitterIsCurrentlyLinked) { // 执行解绑Twitter的异步操作 await firebase.auth().currentUser.unlink('twitter.com'); actionType = 'UNLINK_TWITTER_SUCCESS'; } else { // 执行关联Twitter的异步操作 const provider = new firebase.auth.TwitterAuthProvider(); await firebase.auth().currentUser.linkWithPopup(provider); actionType = 'LINK_TWITTER_SUCCESS'; } // 发送成功的普通对象action dispatch({ type: actionType, payload: contributorUserId }); } catch (error) { // 处理错误,发送失败的action const errorActionType = twitterIsCurrentlyLinked ? 'UNLINK_TWITTER_FAILURE' : 'LINK_TWITTER_FAILURE'; dispatch({ type: errorActionType, payload: error.message }); } }; };
关键提醒
- 别让Thunk action creator直接返回Promise(async函数默认返回Promise),必须让它返回一个接受
dispatch的函数,在这个函数内部写async/await逻辑。 - 最终发给Redux的action必须是普通对象(要有
type属性,payload可选)。 - 用
try/catch包裹异步操作,处理关联/解绑过程中的错误,避免未捕获异常导致应用崩溃。
内容的提问来源于stack exchange,提问作者Juan L
相关产品推荐
相关产品推荐

