Redux报错Actions must be plain objects,疑Redux Thunk配置问题求解决
搞定Redux里的"Actions must be plain objects"错误(和Redux Thunk有关)
嘿,我一眼就看出问题出在哪了——你的Redux Store没正确配置Redux Thunk中间件!
Redux默认只认普通对象当action,但你写的addBiller返回的是个异步函数,这时候必须靠Thunk中间件来“翻译”这个函数,让Redux能处理它。没加Thunk的话,Redux拿到这个函数直接就懵了,于是抛出那个错误。
修复步骤走一波:
先确认装了redux-thunk
要是还没装,先在项目里装一下:npm install redux-thunk # 用yarn的话就是 yarn add redux-thunk修改Store文件,把Thunk加进去
你的Store代码里得引入Thunk,然后通过applyMiddleware把它传给createStore,具体改完应该是这样:import { createStore, combineReducers, applyMiddleware } from "redux"; import thunk from "redux-thunk"; // 引入Thunk中间件 import billerReducer from "./path/to/your/billerReducer"; // 换成你实际的reducer路径 // 合并reducers(如果有多个的话) const rootReducer = combineReducers({ billers: billerReducer // 这里的键名根据你的业务来定 }); // 关键:用applyMiddleware把Thunk注入进去 const store = createStore( rootReducer, applyMiddleware(thunk) ); export default store;
额外检查点:
- 你的
addBilleraction创建函数写法是对的,确实返回了异步函数,这部分不用改 - 组件里dispatch这个action的时候,确保是这么写的:
dispatch(addBiller(yourBillerData)),别把函数本身直接丢给dispatch(一般用useDispatch或者connect的话不会犯这个错)
等你配置好Thunk后,中间件会自动拦截那个异步action函数,先执行axios请求,等请求完成后再dispatch真正的普通对象action(就是你写的{ type: "ADD_BILLER", payload: res.data }),这样Redux就能正常处理了~
内容的提问来源于stack exchange,提问作者Sidharth Jamuar
相关产品推荐
相关产品推荐

