下单跳转订单页报错TypeError: Cannot read properties of undefined (reading 'order')
解决下单跳转订单页时的TypeError问题
下单后订单已成功创建(后端返回201状态码,数据库orders集合中存在对应订单及ID),但执行跳转代码 navigate(/order/${data.order._id}) 时,控制台抛出错误:
TypeError: Cannot read properties of undefined (reading 'order')
相关代码片段
前端placeorderScreen.jsx关键代码
const placeOrderHandler = async () => { try { dispatch({ type: 'Create_Request' }); const { data } = axios.post( // 此处缺少await关键字 '/api/orders', { orderItems: cart.cartItems, shippingAddress: cart.shippingAddress, paymentMethod: cart.paymentMethod, itemsPrice: cart.itemsPrice, shippingPrice: cart.shippingPrice, taxPrice: cart.taxPrice, totalPrice: cart.totalPrice, }, { headers: { authorization: `Bearer ${userInfo.token}`, }, } ); ctxDispatch({type: 'Cart_Clear'}); dispatch({type: 'Create_Success'}); localStorage.removeItem('cartItems'); navigate(`/order/${data.order._id}`) } catch (err) { dispatch({ type: 'Create_Fail' }); toast.error(getError(err)); console.log(err); } };
后端orderRoutes.js代码
orderRouter.post('/',isAuth, expressAsyncHandler(async(req,res) => { const newOrder = new Order({ orderItems: req.body.orderItems.map((x) => ({...x, product: x._id})), shippingAddress: req.body.shippingAddress, paymentMethod: req.body.paymentMethod, itemsPrice: req.body.itemsPrice, shippingPrice: req.body.shippingPrice, taxPrice: req.body.taxPrice, totalPrice: req.body.totalPrice, user: req.user._id, }) const order = await newOrder.save(); res.status(201).send({message: 'New Order Created', order}); }))
错误原因分析
前端代码中调用axios.post时未添加await关键字,导致const { data } = axios.post(...)解构的不是后端返回的响应数据,而是axios.post返回的Promise对象。Promise对象中不存在order属性,因此访问data.order._id时抛出Cannot read properties of undefined (reading 'order')错误。
解决方案
在axios.post前添加await,确保等待异步请求完成后再获取响应数据:
const { data } = await axios.post( '/api/orders', // 请求体和请求配置保持不变 );
修改后,data将正确获取后端返回的{message: 'New Order Created', order}对象,此时访问data.order._id就能拿到订单ID,正常跳转到订单页面。
内容的提问来源于stack exchange,提问作者Krishnadev. V
相关产品推荐
相关产品推荐

