Javascript 承诺在使用效果内未正确处理
我的组件顶部有以下代码:Javascript 承诺在使用效果内未正确处理,javascript,reactjs,typescript,Javascript,Reactjs,Typescript,我的组件顶部有以下代码: export default function Product({product, preview, menu}) { const [cartItems, setCartItems] = useState([]) const [cartTotal, setCartTotalPrice] = useState() const currentCartId = Cookies.get("cartId") useEffec
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)
}
}
}, [])
...
但我得到了以下错误:
如果
尝试
包装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)
//}
}
}, [])
...