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

Vue.js报错:Cannot set properties of undefined (setting) 赋值问题咨询

Vue中Cannot set properties of undefined错误处理

你遇到的错误是因为filter回调里的普通function会绑定自身的this,这个this并不是Vue组件实例,所以无法访问this.qty_to_order。而仅打印的代码能运行,是因为它不需要访问组件实例的this。

以下是几种修改方案:

方案1:使用箭头函数

箭头函数不会绑定自身的this,会继承外层上下文的this(也就是Vue组件实例):

showQty(product_id) {
    this.carts.filter((cart) => {
        if (cart.product_id === product_id) {
            this.qty_to_order = cart.qty_to_order
        }
    })
}

方案2:提前保存组件实例的this

在回调外把组件的this存到变量里,回调内用这个变量访问组件属性:

showQty(product_id) {
    const self = this
    this.carts.filter(function(cart) {
        if (cart.product_id === product_id) {
            self.qty_to_order = cart.qty_to_order
        }
    })
}

优化建议:用find替代filter

filter是用来过滤数组返回所有匹配项的新数组,而你只需要找到第一个匹配的购物车项,用find更高效,找到后直接赋值:

showQty(product_id) {
    const targetCart = this.carts.find(cart => cart.product_id === product_id)
    if (targetCart) {
        this.qty_to_order = targetCart.qty_to_order
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 16:45:57