当我已经在 catch 块中抛出 err 时得到未处理的 Promise 拒绝

Getting unhandled Promise rejection when I already throw err in the catch block

在我的 redux 中,我得到了这个 axios get 调用正如你所看到的,我已经在这里抛出了错误

export const getShippingMethodById = (token, id) => {
    return (dispatch) => {
        const config = {
            headers: {
                Authorization: `bearer ${token}`,
                'Content-Type': 'application/json',
            },
        };
        return axios
            .get(`${baseUri}/api/checkout/GetShippingById?addressId=${id}`, config)
            .then((res) => {
                dispatch({
                    type: FETCH_SHIPPING_METHOD_BY_ID,
                    payload: res.data.shippingInfos,
                });
            })
            .catch((err) => {
                console.log(err);
                throw err;
                alert('Cannot connect to server');
            });
    };
};

在功能组件中,在 useEffect 挂钩中我调用了这个函数

useEffect(() => {
    let splitText = cartList?.OrderDTO?.DeliveryCountry;
    let deliveryAddressId = splitText?.split(',');
    if (
      cartList.OrderDTO?.DeliveryCountry !== '' &&
      deliveryAddressId !== undefined
    ) {
      dispatch(
        getShippingMethodById(token.access_token, Number(deliveryAddressId[1])),
      ).then((res) => {
        console.log(res);
      });
    } else {
      dispatch(
        getShippingMethodById(
          token.access_token,
          cartList.OrderDTO?.CustomerAddressId,
        ),
      ).then((res) => {
        console.log(res);
      });
    }
  }, [cartList]);

但是当这个组件被加载时 我收到这个错误

因为我已经处理了 promise 拒绝,为什么我会收到这个错误?

因为您在 catch 块中使用 throw err;。您需要将其删除。您可以在此处阅读有关 throw 的更多信息:https://developer.mozilla.org/vi/docs/Web/JavaScript/Reference/Statements/throw

catch 中抛出的错误不会被正在执行的同一个 catch 块捕获。这意味着您正在向您的 UI 代码返回一个 Promise 拒绝,然后应该在那里捕获错误。将 catch 添加到 Promise 链。

useEffect(() => {
  let splitText = cartList?.OrderDTO?.DeliveryCountry;
  let deliveryAddressId = splitText?.split(',');
  if (
    cartList.OrderDTO?.DeliveryCountry !== '' &&
    deliveryAddressId !== undefined
  ) {
    dispatch(
      getShippingMethodById(token.access_token, Number(deliveryAddressId[1])),
    ).then((res) => {
      console.log(res);
    }).catch(error => {
      // handle rejected Promise or any other error from this chain
    });
  } else {
    dispatch(
      getShippingMethodById(
        token.access_token,
        cartList.OrderDTO?.CustomerAddressId,
      ),
    ).then((res) => {
      console.log(res);
    }).catch(error => {
      // handle rejected Promise or any other error from this chain
    });
  }
}, [cartList]);

或者干脆去掉重新抛出的错误:

return axios
  .get(`${baseUri}/api/checkout/GetShippingById?addressId=${id}`, config)
  .then((res) => {
    dispatch({
      type: FETCH_SHIPPING_METHOD_BY_ID,
      payload: res.data.shippingInfos,
    });
  })
  .catch((err) => {
    console.log(err);
    // no error rethrow
    alert('Cannot connect to server');
  });