使用ViteJS与redux-mock-store时遇dispatch报错:Actions必须是纯对象
问题解决:redux-mock-store触发“Actions必须是纯对象”错误
问题原因
你调用的fetch是一个异步Action Creator(返回的是函数而非纯对象),但redux-mock-store默认不支持处理异步Action,必须手动配置对应的中间件(比如redux-thunk)才能识别这类异步操作。
解决步骤
1. 安装并配置redux-thunk中间件
首先确保安装了redux-thunk(开发依赖即可):
npm install redux-thunk --save-dev
然后在创建mock store时,把thunk加入中间件数组:
import configureMockStore from 'redux-mock-store'; import thunk from 'redux-thunk'; // 配置带thunk中间件的mock store const middlewares = [thunk]; const mockStore = configureMockStore(middlewares);
2. 确认异步Action Creator格式正确
你的fetch Action Creator必须符合thunk的规范——返回一个接收dispatch的函数,示例:
export const fetch = ({ url }) => async (dispatch) => { try { const response = await fetch(url); const data = await response.json(); // 异步完成后触发同步action dispatch({ type: 'FETCH_DATA_SUCCESS', payload: data }); } catch (error) { dispatch({ type: 'FETCH_DATA_FAILED', payload: error.message }); } };
3. 测试时的正确用法
在测试代码中创建store实例,再dispatch异步Action:
// 创建初始状态的mock store const store = mockStore({ data: [] }); // 触发异步action store.dispatch(fetch({ url: '/your-api-url' })); // 可以通过store.getActions()获取所有触发的同步action,用于断言 const actions = store.getActions(); expect(actions[0].type).toBe('FETCH_DATA_SUCCESS');
内容的提问来源于stack exchange,提问作者Jair Nunes
相关产品推荐
相关产品推荐

