首页 > 解决方案 > 承诺在 useEffect 内部未正确处理

问题描述

我的组件顶部有以下代码:

export default function Product({product, preview, menu}) {
    const [cartItems, setCartItems] = useState([])
    const [cartTotal, setCartTotalPrice] = useState()

    const currentCartId = Cookies.get("cartId")

    useEffect(() => {
        const getCurrentCart = async () => {
            const cart = await getCartById(currentCartId)

            setCartItems(cart.lineItems)
            setCartTotalPrice(cart.totalPrice.centAmount)
            Cookies.set("cartVersion", cart.version)
        }

        if (currentCartId && cartItems?.length === 0) {
            try {
                getCurrentCart()
            } catch (e) {
                console.log(e)
            }
        }
    }, [])
...

但我收到以下错误:

在此处输入图像描述

标签: javascriptreactjstypescript

解决方案


try包装getCurrentCart()调用实际上不会捕获,因为效果本身不是异步的。你需要打电话getCurrentCart().catch()

export default function Product({product, preview, menu}) {
    const [cartItems, setCartItems] = useState([])
    const [cartTotal, setCartTotalPrice] = useState()

    const currentCartId = Cookies.get("cartId")

    useEffect(() => {
        const getCurrentCart = async () => {
            const cart = await getCartById(currentCartId)

            setCartItems(cart.lineItems)
            setCartTotalPrice(cart.totalPrice.centAmount)
            Cookies.set("cartVersion", cart.version)
        }
        
        // Make another aysnc function that can catch
        const doStuff = async () => {
          if (currentCartId && cartItems?.length === 0) {
              try {
                  getCurrentCart()
              } catch (e) {
                  console.log(e)
              }
          }
        };
        
        // Call the function that will call getCurrentCard from
        // a place that can catch correctly
        doStuff();
        
        // OR
        if (currentCartId && cartItems?.length === 0) {
            // The try will do nothing because it would only catch
            // the creation of the promise, not the error that might
            // occur within it
            //try {
                getCurrentCart().catch(e => {
                  console.log(e);
                })
            //} catch (e) {
            //    console.log(e)
            //}
        }
    }, [])
...

推荐阅读