反应 Redux rejectWithValue() 不工作

React Redux rejectWithValue() not working

我目前遇到一个问题,当我尝试在我的节点获取请求失败时拒绝一个值时,thunkApi.rejectWithValue() 无法正常工作。但是,当我的请求待处理或完成时,它工作正常。 这是我的切片:

export const userSlice = createSlice({
  name: "user",
  initialState: initialState as User,
  reducers: {
    ...
  },
  extraReducers: (builder) => {
    ...
    builder.addCase(changePassUser.pending, (state) => {
      GGLog("FETCHING CHANGEPASS API...");
      state.isFetching = true;
      return state;
    });
    builder.addCase(changePassUser.fulfilled, (state, { payload }) => {
      GGLog("FULFILLED CHANGEPASS:", JSON.stringify(payload));
      state.isFetching = false;
      state.isSuccess = true;
      state.isError = false;
      return state;
    });
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    builder.addCase(changePassUser.rejected, (state, { payload }: any) => {
      GGLog("REJECTED CHANGEPASS:", JSON.parse(payload));
      state.isFetching = false;
      state.isError = true;
      state.errorMessage = payload.data;
      return state;
    });
  },
});

这是我的声音:

export const changePassUser = createAsyncThunk(
  "users/password/update",
  async ({ oldpassword, newpassword }: RegisterParameters, thunkAPI) => {
    try {
      const res = await changePassApi.changePass.return({
        oldpassword: oldpassword,
        newpassword: newpassword,
      });
      GGLog("API_CHANGEPASS_RES:", res);
      const data = await res.json();
      if (res.ok) {
        GGLog("API_DATA_RESPONSE_OK: ", data);
        const tokenData = JSON.stringify(res.headers);
        const token = JSON.parse(tokenData).map["x-auth"];
        await localStorage.store("token", token);
        return data;
      } else {
        GGLog("API_DATA_RESPONSE_NOK: ", data);
        return thunkAPI.rejectWithValue(data);
      }
    } catch (e) {
      GGLog("Error while fetching Login API => ", e);
      return thunkAPI.rejectWithValue(e);
    }
  }
);

这是控制台中的结果: Console output

有什么想法吗?我错过了什么吗? 谢谢:)

好的,我发现了我的问题,我只是专注于 thunk 而没有注意 promise rejection。我试图解析一个不存在的 JSON...只需删除切片中的 GGLog("REJECTED CHANGEPASS:", JSON.parse(payload));。 现在一切正常!