You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue.js组件挂载后更新运费报错:无法读取price属性

Vue组件挂载修改运费时出现TypeError错误

相关代码与信息

模板代码

<div>
  <input
   type="radio"
  name="order"
   checked="checked"                   
    @change="onChooseShipping('normal')"
 /> Normal
</div>

Mounted钩子请求代码

async mounted() {
    try {
        let response = await axios.post("http://localhost:5000/api/shipment", {
          shipment: normal
        });
        console.log(response)
        this.$store.commit("setShipping", {
          price: response.shipment.price,
          estimatedDelivery: response.shipment.estimated
        });
        this.price = response.shipment.price;
        this.estimatedDelivery = response.shipment.estimated;
      } catch (err) {
        console.log(err)
      }
}

接口返回JSON数据

{
    "success": true,
    "shipment": {
        "estimated": "Tuesday August 30th",
        "price": 13.98
    }
}

错误信息

TypeError: Cannot read properties of undefined (reading 'price')
    at VueComponent.mounted

解决步骤

  1. 修正Axios响应数据的访问路径
    Axios会把接口返回的实际数据封装在响应对象的data属性中,直接访问response.shipment会得到undefined,进而导致读取price失败。需将所有response.shipment替换为response.data.shipment:

修改后的代码:

async mounted() {
    try {
        let response = await axios.post("http://localhost:5000/api/shipment", {
          shipment: normal
        });
        console.log(response.data) // 打印实际返回的数据确认结构
        this.$store.commit("setShipping", {
          price: response.data.shipment.price,
          estimatedDelivery: response.data.shipment.estimated
        });
        this.price = response.data.shipment.price;
        this.estimatedDelivery = response.data.shipment.estimated;
      } catch (err) {
        console.log(err)
      }
}
  1. 检查normal变量是否定义
    代码中shipment: normal里的normal如果是字符串类型,需要用引号包裹成shipment: 'normal',否则会因变量未定义抛出新的错误。

内容的提问来源于stack exchange,提问作者xander

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 15:15:35