我已经用打字稿设置了redux thunk函数,如下所示:
export const fetchActivities = (): AppThunk => async dispatch => {
dispatch(fetchActivitiesRequest())
try {
const res = await fetch("/activities")
const body = await res.json()
dispatch(fetchActivitiesSuccess(body))
} catch (err) {
dispatch(fetchActivitiesError(err))
}
}
AppThunk只是从ThunkAction类型派生的类型,具有以下类型参数:
export type AppThunk<ReturnType = void> = ThunkAction<ReturnType, {}, null, Action<string>>
我的问题是,当我尝试为我的操作设置单元测试时,以及当我尝试分派这样的重击操作时:
const middlewares = [thunk]
const mockStore = configureMockStore(middlewares)
const store = mockStore({ activities: [] })
store.dispatch(actions.fetchActivities())
我收到以下错误消息:
Argument of type 'ThunkAction<void, {}, null, Action<string>>' is not assignable to parameter of type 'AnyAction'.
Property 'type' is missing in type 'ThunkAction<void, {}, null, Action<string>>' but required in type 'AnyAction'.ts(2345)
尽管没有成功,但我一直在尝试寻找解决此问题的方法。大多数建议都说尝试向泛型中添加任何参数以进行分派,因此dispatch<any>(actions.fetchActivities())
。尽管这样做可以防止键入错误,但是只会调度thunk中的第一个操作,而try和catch语句中的所有内容都将被忽略。
有人对如何解决此问题有任何建议吗?
首先:因此,不执行任何其他操作的重击只能具有一个含义:dispatch
的其他调用很可能从未到达。您确定对fetch
的通话会终止吗?它可能会永远等待答案或类似的东西。
第二,您的键入问题:普通的Dispatch
类型默认不支持thunk。您的Dispatch<any>
解决方案还可以。否则,您可以将dispatch
函数从ThunkDispatch
包中强制转换为redux-thunk
。
编辑:对不起,这只是[[looked]完全类似于RTK错误,但是有所不同。(原始的,可能是错误的答案)
这是RTK中的一个已知错误,其中包含currently open PR可以解决该问题-由于我生病了,所以我还没有定下来,但是您可以使用CI构建,直到我们推出一个新的版。您可以通过
安装它yarn add https://pkg.csb.dev/reduxjs/redux-toolkit/commit/933aa4a1/@reduxjs/toolkit
要么npm i https://pkg.csb.dev/reduxjs/redux-toolkit/commit/933aa4a1/@reduxjs/toolkit