【问题标题】:createAsyncThunk throws error but case rejected does not get triggeredcreateAsyncThunk 引发错误,但案例拒绝不会被触发
【发布时间】:2021-08-02 11:52:16
【问题描述】:

我正在使用以下 createAsyncThunk 删除数据库中的应用程序。

由于某种原因,提取无法正常工作。 handleFetchErrors 如果响应不正确则抛出错误

export const handleFetchErrors = (response: Response) => {
        if (!response.ok) {
            throw Error(response.statusText)
        }
}

export const deleteApplication = createAsyncThunk("applications/deleteApplication", async (data: any) => {
    try {
        const response = await fetch(`/api/application/${data.id}`, {
            method: "DELETE",
            headers: {
                'Accept': 'application/json',
                "Content-Type": "application/json",
            },
        });
        //fixme: call still gets fulfilled although I am throwing an error
        handleFetchErrors(response);
        return (data.id);
    } catch (e) {
        console.error(e);
    }
})

在我的createSlice 中,我将这些额外的Reducers 用于大写

 .addCase(deleteApplication.fulfilled, (state, action) => {
                state.status = DataFetchingStatus.succeeded
                state.applications = state.applications.filter(application => application.id !== action.payload)
            })
            .addCase(deleteApplication.rejected, (state, action) => {
                state.status = DataFetchingStatus.failed
                state.error = action.payload
            })

deleteApplication.fulfilled 被触发,而不是 deleteApplication.rejected

我错过了什么吗?

【问题讨论】:

    标签: reactjs redux redux-thunk


    【解决方案1】:

    handleFetchErrors 函数抛出一个错误,但是这个错误被deleteApplication 捕获并且仅仅作为控制台消息打印。因此,deleteApplication.rejected 永远不会被发送。我建议(a)不要发现错误;或 (b) 在 catch 块中重新抛出错误。

    【讨论】:

      猜你喜欢
      • 2013-12-20
      • 2014-05-21
      • 1970-01-01
      • 1970-01-01
      • 2020-09-16
      • 1970-01-01
      • 2020-02-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多