You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用redux-mock-store集成thunk遇类型及函数错误求助

Redux-Mock-Store 集成 Redux-Thunk 时的类型错误与执行异常解决

问题详情

使用 Jest、React 和 TypeScript 开发项目,尝试通过 redux-mock-store 模拟 Redux Store 并集成 redux-thunk 中间件,以支持 dispatch thunk 函数。按官方文档配置时出现类型不匹配错误:

Type 'typeof import("random_path/redux-thunk/dist/redux-thunk")' is not assignable to type 'Middleware<{}, any, Dispatch>'.
Type 'typeof import("random_path/redux-thunk/dist/redux-thunk")' provides no match for the signature '(api: MiddlewareAPI<Dispatch, any>): (next: Dispatch) => (action: any) => any'.

用 const mockStore = configureStore([thunk as any]); 绕过类型检查后,又触发新错误:TypeError: middleware is not a function。严格遵循官方文档仍无法解决,寻求帮助。

复现代码

import configureStore from "redux-mock-store";
import thunk from "redux-thunk";

const mockStore = configureStore([thunk]);

it("should handle fetchCharacterDataAsync", async () => {
  const characterInitialState = {
    data: null,
    isLoading: false,
    error: undefined,
  };
  const store = mockStore(characterInitialState);
  await store.dispatch(fetchCharacterDataAsyncTHUNK("1011334") as any);
});

解决方案

1. 修正 Redux-Thunk 中间件的使用方式

Redux-Thunk v2.x+ 的默认导出是一个工厂函数,必须调用它才能生成有效的中间件实例。之前直接传递 thunk 模块而非调用后的函数,导致中间件类型不匹配且执行时触发函数类型错误。正确写法:

import configureStore from "redux-mock-store";
import thunk from "redux-thunk";

// 调用 thunk() 生成中间件实例
const mockStore = configureStore([thunk()]);

2. 解决 TypeScript 类型问题

无需用 as any 绕过类型检查,只要正确调用 thunk(),TypeScript 就能自动识别中间件类型。若仍有类型提示问题,可显式指定中间件类型:

import { Middleware } from "redux";
import configureStore from "redux-mock-store";
import thunk from "redux-thunk";

const middlewares: Middleware[] = [thunk()];
const mockStore = configureStore(middlewares);

3. 确认依赖版本兼容性

确保 redux-mock-store 和 redux-thunk 的版本相互兼容:

  • 使用最新稳定版的 redux-mock-store,避免版本过低导致的类型不兼容问题
  • 若项目使用 Redux Toolkit,更推荐直接使用 RTK 自带的 configureStore 配合 Jest 进行测试,RTK 原生支持 thunk,且类型系统更完善,无需额外配置 redux-mock-store

内容的提问来源于stack exchange,提问作者SigurdWatt

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 06:23:22