类型'AsyncThunkAction<any, number, {}>'的参数不能分配给类型为'AnyAction'参数,使用打字稿的redux错误



我有一个分派函数:

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)
}

异步思维函数是这样的:

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类型看起来像这样,它来自redux typescript文档:

export type AppDispatch = typeof store.dispatch

问题在

dispatch(fetchCity(parseInt(target.id)))

错误提示:类型为"AsyncThunkAction<any,>"的参数不能赋值给类型为"AnyAction"的参数。

我甚至试着这样做:

dispatch(fetchCity(1))

我得到了相同的错误。

我该怎么办,我很困惑,因为我做的所有这些都和在redux文档中一样?

我也遇到了同样的问题。在我的例子中,我在我的商店中写错了这一行。

export const store: EnhancedStore = configureStore(...)

EnhancedStore类型返回一个不支持thks的分派。将其更改为:

export const store = configureStore(...)

允许TypeScript将类型推断为ToolkitStore,从而修复了它。

如果你的store不是一个ToolkitStore,再看看你是如何初始化它的

最新更新