Redux+TypeScript报错:AsyncThunkAction无法赋值给AnyAction类型
我有一个dispatch函数:
const dispatch = useAppDispatch() const handleFetch = (e: React.MouseEvent<HTMLAnchorElement>) => { const target = e.target as Element dispatch(fetchCity(parseInt(target.id))) localStorage.setItem('location', target.id) }
异步thunk函数如下:
export const fetchCity = createAsyncThunk('city/fetchCity', async (id: number) => { const res = await fetch(`${apiUrl}/${id}`) .then(res => res.json()) return res })
我的useAppDispatch钩子与Redux TypeScript文档写法一致:
import type { AppDispatch } from "./redux/store"; export const useAppDispatch: () => AppDispatch = useDispatch
AppDispatch类型定义同样来自官方文档:
export type AppDispatch = typeof store.dispatch
问题出在dispatch(fetchCity(parseInt(target.id))),报错信息:Argument of type 'AsyncThunkAction<any, number, {}>' is not assignable to parameter of type 'AnyAction'。尝试dispatch(fetchCity(1))仍报相同错误,按文档配置却遇此问题,该如何解决?
核心问题是你的AppDispatch类型未正确包含Redux Thunk的异步action处理能力,导致TypeScript认为dispatch只能接收普通AnyAction类型。按以下步骤排查修复:
1. 确认Store配置正确集成Thunk中间件
Redux Toolkit的configureStore默认已包含Thunk中间件,但如果手动配置了middleware,需确保未移除它:
// redux/store.ts import { configureStore } from '@reduxjs/toolkit'; import cityReducer from './features/city/citySlice'; // 替换为你的slice实际路径 export const store = configureStore({ reducer: { city: cityReducer, }, // 若手动配置middleware,需保留默认的Thunk(如下代码可省略,因为configureStore默认已包含) // middleware: (getDefaultMiddleware) => getDefaultMiddleware(), }); export type AppDispatch = typeof store.dispatch; export type RootState = ReturnType<typeof store.getState>;
2. 确保组件正确导入自定义useAppDispatch
检查组件中是否使用的是你定义的useAppDispatch,而非Redux原生的useDispatch:
// 组件文件内 import { useAppDispatch } from '../redux/store'; // 路径需与实际文件匹配 import { fetchCity } from '../redux/features/city/citySlice'; const dispatch = useAppDispatch(); const handleFetch = (e: React.MouseEvent<HTMLAnchorElement>) => { const target = e.target as Element; const cityId = parseInt(target.id, 10); // 建议添加进制参数,避免非十进制解析异常 dispatch(fetchCity(cityId)); localStorage.setItem('location', target.id); };
3. 优化fetchCity的类型定义(可选但推荐)
给createAsyncThunk明确指定返回值类型,避免any类型带来的隐患:
// 先定义城市数据类型 interface City { id: number; name: string; // 根据实际接口返回字段补充其他属性 } export const fetchCity = createAsyncThunk<City, number>( 'city/fetchCity', async (id: number) => { const res = await fetch(`${apiUrl}/${id}`); return res.json() as Promise<City>; } );
如果完成以上步骤仍报错,尝试重启TypeScript语言服务(VSCode中按Ctrl+Shift+P,选择"TypeScript: Restart TS Server"),缓存问题可能导致类型识别异常。
内容的提问来源于stack exchange,提问作者Isa Seferović

