Redux报错:Actions必须是纯对象,实际类型为string的排查求助
问题解决:Redux "Actions must be plain objects" 错误
错误原因
你在friendUser action里直接执行dispatch(id),这里的id是字符串类型,而Redux要求所有dispatch的action必须是包含type字段的纯对象,这就是触发报错的核心原因。
修复步骤
- 定义Action类型常量
在actions.js里先声明action的类型标识:
export const FRIEND_USER_SUCCESS = 'FRIEND_USER_SUCCESS';
- 修正Action的dispatch逻辑
把原来直接dispatch字符串的代码,改成dispatch符合要求的纯对象:
export const FRIEND_USER_SUCCESS = 'FRIEND_USER_SUCCESS'; export const friendUser = (id) => async (dispatch) => { try { await api.friendUser(id); // dispatch带type的纯对象,可携带id作为payload供reducer使用 dispatch({ type: FRIEND_USER_SUCCESS, payload: id }); } catch (error) { console.log(error); // 可选:添加失败场景的action处理 // dispatch({ type: 'FRIEND_USER_FAILURE', payload: error }) } }
- 确保Store配置了Redux-Thunk中间件
因为你的action是异步函数(使用了async/await),必须依赖redux-thunk中间件才能让Redux支持这种异步action。如果还没配置,在store创建文件里添加:
import { createStore, applyMiddleware } from 'redux'; import thunk from 'redux-thunk'; import rootReducer from './reducers'; const store = createStore( rootReducer, applyMiddleware(thunk) ); export default store;
- 在Reducer中处理该Action(按需)
如果需要更新Redux状态,在对应reducer里添加对FRIEND_USER_SUCCESS类型的处理:
import { FRIEND_USER_SUCCESS } from '../actions'; const initialState = { friends: [] }; const userReducer = (state = initialState, action) => { switch(action.type) { case FRIEND_USER_SUCCESS: return { ...state, // 示例:将id加入friends数组,根据你的业务需求调整 friends: [...state.friends, action.payload] }; default: return state; } }; export default userReducer;
关键说明
Redux的核心规则是:action必须是带有type字段的纯对象,reducer通过type判断要执行的状态更新逻辑。直接dispatch字符串、数字或其他非对象类型的值,都会触发这个错误。另外,异步action(比如调用API的逻辑)必须借助redux-thunk这类中间件才能被Redux识别处理。
内容的提问来源于stack exchange,提问作者hamsheena
相关产品推荐
相关产品推荐

