javascript - 承诺在 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)
}
}
}, [])
...
但我收到以下错误:
解决方案
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)
//}
}
}, [])
...
推荐阅读
- python - 我可以在 buildroot 中安装 wheel 包吗?
- bash - bash 仅针对用户输入的第一个字符读取超时
- python - 用python的正则表达式匹配多组字符
- android - Dagger2 作用域片段的问题
- bokeh - 如何提供从 JSON 加载的 Bokeh 文档?
- unity3d - 未找到跨脚本变量
- swift - 如何在swift中添加两个具有索引值的数组?
- swift - 从 GKTurnBasedMatchMakerViewController 检索 GKTurnBasedMatch 对象 - Swift 4
- android-studio - 如何设置 ButterKnife 逐行代码样式?
- c# - WPF 跳跃或闪烁按钮