【问题标题】:Argument of type 'ThunkAction' is not assignable to parameter of type 'AnyAction'“ThunkAction”类型的参数不能分配给“AnyAction”类型的参数
【发布时间】:2020-05-19 19:33:27
【问题描述】:

我已经使用 typescript 设置了一个 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&lt;any&gt;(actions.fetchActivities())。虽然这可以阻止输入错误,但只有 thunk 中的第一个操作会被调度,而 try 和 catch 语句中的所有内容都将被忽略。

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

【问题讨论】:

    标签: typescript redux react-redux redux-thunk


    【解决方案1】:

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

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

    其次,您的打字问题:普通的Dispatch 类型默认不支持thunk。您使用Dispatch&lt;any&gt; 的解决方案没问题。否则,您可以将 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

    【讨论】:

    • 谢谢。我为 API 准备的模拟似乎有问题。通过使 API 模拟再次工作,并将调度转换为 ThunkDispatch,错误得到了修复。
    猜你喜欢
    • 2020-07-18
    • 2021-10-19
    • 2022-01-05
    • 2020-11-13
    • 2021-11-18
    • 2019-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多