'ThunkAction' 类型的参数不能分配给 'AnyAction' 类型的参数

Argument of type 'ThunkAction' is not assignable to parameter of type 'AnyAction'

我已经用这样的打字稿设置了一个 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>>

我的问题是,当我尝试为我的操作设置单元测试时,以及当我尝试像这样发送 thunk 操作时:

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 语句中的所有内容。

有人对如何解决这个问题有任何建议吗?

这是两个截然不同的问题。任何方式的类型都不会影响运行时行为。

首先:所以你的 thunk 没有触发任何其他操作只能有一个含义:对 dispatch 的其他调用很可能永远不会到达。 您确定您对 fetch 的呼叫会终止吗?它可能永远等待答案或类似的东西。

其次,您的输入问题:正常的 Dispatch 类型默认不支持 thunk。您使用 Dispatch<any> 的解决方案没问题。否则,您可以将 dispatch 函数从 redux-thunk 包转换为 ThunkDispatch

编辑:抱歉,这 看起来 与 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