Redux报错:Actions必须是纯对象,排查store配置或异步action问题
解决Redux报错「Actions must be plain objects. Use custom middleware for async actions」
Hey there! Let's break down why you're seeing this error and how to fix it quickly.
问题根源
Redux 默认只接受普通 JavaScript 对象作为 action,但你的 addHousehold 是一个异步 action(它返回的是函数,而非普通对象)—— 这种写法属于 "thunk" 类型的 action,Redux 本身无法处理这类异步逻辑,必须借助对应的中间件,最常用的就是 redux-thunk。
修复步骤
安装 redux-thunk(如果还没安装的话):
在项目终端运行以下命令:npm install redux-thunk # 或者用 yarn yarn add redux-thunk将中间件添加到 Redux Store 中
创建 Store 时,通过applyMiddleware引入 thunk,示例代码如下:import { createStore, applyMiddleware } from 'redux'; import thunk from 'redux-thunk'; import rootReducer from './path/to/your/rootReducer'; const store = createStore( rootReducer, applyMiddleware(thunk) // 这一步是核心配置! ); export default store;注意:如果你使用的是 Redux Toolkit(现在官方推荐的写法),thunk 已经默认集成在内,无需手动添加。
可选:简化你的 action 代码
你的 action 逻辑是可行的,但可以借助async/await本身返回 Promise 的特性,去掉冗余的new Promise包裹,让代码更简洁:export const addHousehold = user => async dispatch => { const hasHousehold = await getUsersHouseholdByUserId(user.uid); if (hasHousehold) { throw new Error( 'You have already generated a household. Please complete the setup steps.' ); } return dispatch(createHousehold(user)); };调用这个 action 时,依然可以通过
.catch()来捕获错误,效果和之前一致。
最后确认
配置好 thunk 中间件后,Redux 就能正确识别你的异步 action 函数,那个报错应该就会消失了。
内容的提问来源于stack exchange,提问作者Le Moi
相关产品推荐
相关产品推荐

