You need to enable JavaScript to run this app. Vue.js computed调用方法时出现Cannot read property 'units'报错如何解决
优惠活动
大模型
产品
解决方案
定价
更多

Vue.js computed调用方法时出现Cannot read property 'units'报错如何解决

问题根因
  • 直接报错原因:data中building的初始值是空对象{},首次执行computed的useExistingBuilding时,不满足this.building === 'New'的判断,会把空对象作为参数传给formatUnits,find方法匹配不到对应buildingID的项,返回undefined,读取undefined.units就抛出了对应错误。
  • 逻辑设计错误:computed的设计原则是无副作用的纯函数,不应该在computed内部修改data里的units值,即使绕开报错,后续也可能出现依赖更新不及时、重复执行等不可预期的问题。
修复方案

把修改units的逻辑从computed挪到watch侦听器里,监听building的变化来更新units即可:

export default {
  name: "Form",
  data: () => ({
    // 初始值设为null或者和业务匹配的初始ID,不要用空对象
    building: null,
    buildings: [
      {
        units: [],
        buildingID: "<an ID according to a custom format>",
      }
    ],
    units: [],
  }),
  watch: {
    // 监听building的变化,动态更新units
    building: function(newVal) {
      if (newVal === 'New') {
        // 新建楼宇的话清空units或者设为默认值
        this.units = []
        return
      }
      const selectedBuilding = this.buildings.find(item => item.buildingID === newVal)
      // 加容错判断,避免匹配不到时报错
      if (selectedBuilding) {
        this.units = selectedBuilding.units
      }
    }
  },
  computed: {
    useExistingBuilding() {
      // computed只做返回值的纯计算,不要有副作用
      return this.building === 'New'
    }
  }
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.22 06:27:03