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

Vue3中使用eval动态设置数组路径变量报Cannot set properties of undefined错误

解决Vue3中使用eval动态访问响应式数组路径报错的问题

问题原因

你遇到的问题本质是Vue的Reactivity Transform(即你用到的$ref和$$语法)与eval的作用域冲突:

  • 用$ref声明的productCategoriesTree会被编译为Vue的响应式代理对象,但eval运行时无法正确识别这个经过编译的变量,它会直接去当前作用域查找原始变量名,导致访问路径时拿到的不是预期的响应式节点,最终触发"Cannot set properties of undefined"错误。
  • 另外eval本身存在安全风险和性能损耗,在Vue项目中完全没必要使用。

解决方案

替换eval,手动实现动态遍历路径的逻辑,安全获取目标节点并修改属性:

修改后的addNewProductCategory函数

// treePath could be [0, 1, 0, 0, 1] - it is dynamic
const addNewProductCategory = (parentCategoryUuid: string, treePath: number[]) => {
    const newProductCategory = {
        uuid: `__NEW-${uuidv4()}`,
        namePlural: 'new',
        parent: { uuid: parentCategoryUuid }
    }

    if (!productCategoriesTree[1].children) {
        productCategoriesTree[1].children = []
    }

    productCategoriesTree[1].children?.push({
        data: newProductCategory as ProductCategory,
        children: [],
    })

    // 手动遍历treePath获取目标节点
    let targetNode: any = productCategoriesTree
    for (const index of treePath) {
        if (!targetNode) break // 路径无效时提前终止,避免报错
        targetNode = targetNode[index]
    }

    // 确认目标节点存在后设置属性
    if (targetNode) {
        targetNode.$folded = false
    }
}

额外说明

  • 这个方法不仅避开了eval的问题,还能在路径无效时做容错处理,防止程序崩溃。
  • 即便你使用的是Vue3标准的ref/reactive响应式API,这个方法依然适用,因为它直接操作响应式对象本身,不会产生作用域冲突问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 02:40:17