createAsyncThunk 抛出错误但未触发拒绝案例

时间:2021-05-12 06:12:16

标签: reactjs redux redux-thunk

我正在使用以下 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 中,我将这些 extraReducers 用于大写

 .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

我错过了什么吗?

1 个答案:

答案 0 :(得分:1)

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