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

删除产品时出现Cannot read properties of undefined (reading 'filter')错误求助

解决方案:修复删除产品时的filter调用错误

报错原因

报错Cannot read properties of undefined (reading 'filter')的核心是products.value.data为undefined,无法调用数组方法filter。通常由以下情况导致:

  • products未正确初始化,缺少data属性
  • 接口返回后products.value的结构不符合预期

修复步骤

1. 确保products初始化正确

如果使用Vue 3的ref,需保证初始值包含data数组:

// 正确初始化方式
const products = ref({ data: [] })

避免直接初始化为ref([]),否则products.value.data会是undefined。

2. 添加空值保护并优化逻辑

在调用filter前用可选链操作符?.做空值检查,同时给axios请求添加错误捕获,避免未处理的promise异常:

const deleteProduct = id => {
  Swal.fire({
    title: 'Are you sure?',
    text: "You won't be able to revert this!",
    icon: 'warning',
    showCancelButton: true,
    confirmButtonColor: '#3085d6',
    cancelButtonColor: '#d33',
    confirmButtonText: 'Yes, delete it!'
  }).then(result => {
    if (result.isConfirmed) {
      axios.delete(`/api/product/${id}`)
        .then(response => {
          // 空值检查确保data存在再执行filter
          if (products.value?.data) {
            products.value.data = products.value.data.filter(
              product => product.id !== id
            )
            Swal.fire('Deleted!', 'Your file has been deleted.', 'success')
          }
        })
        .catch(error => {
          // 捕获请求错误并提示用户
          Swal.fire('Error!', 'Failed to delete product.', 'error')
          console.error(error)
        })
    }
  })
}

3. 验证接口返回数据

确认axios.delete接口是否返回正确响应,若接口会返回更新后的产品列表,可直接替换本地数据:

// 若接口返回更新后的列表,直接替换
products.value = response.data

额外建议

  • 模板中可添加加载状态,避免用户重复点击删除按钮
  • 确保product.id与接口返回的id类型一致(均为数字或字符串),避免filter匹配失败

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 01:55:10