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

MobX实现汽车名称筛选时报Cannot read property 'filter' of undefined错误

报错核心原因
  • 触发报错的直接原因:CarStore构造函数接收cars参数,但导出单例时是无参实例化的(new CarStore())。构造函数中执行this.cars = cars时,因为没有传入入参,会把类定义阶段初始化的完整车辆数组直接覆盖为undefined。后续执行filteredCars计算属性中的this.cars.filter()方法时,因为操作的是undefined,就会抛出Cannot read property 'filter' of undefined错误。
  • 可能触发同类报错的次要原因:MobX依赖注入的key不匹配。Home组件通过inject("CarStore")获取全局store,需要确认根组件的Provider注入store时,对应的键名就是CarStore,如果键名不一致,会导致this.props.CarStore本身为undefined,访问其属性时也会触发同类错误。
具体修复步骤
  1. 修正CarStore的构造函数逻辑
    去掉构造函数中无参场景下的强制赋值,避免把类初始化的车辆数组覆盖为undefined:
    constructor(cars) {
        makeObservable(this, {
            isSorted: observable,
            cars: observable,
            currentPage: observable,
            carsPerPage: observable,
            indexOfLastCar: observable,
            indexOfFirstCar: observable,
            currentCars: computed,
            filter: observable,
            filteredCars: computed,
            currentSortedCars: computed,
            sortedCars: computed,
            setPage: action,
        });
        // 仅当传入有效cars入参时才覆盖初始数据
        if (Array.isArray(cars)) {
            this.cars = cars;
        }
    }
    
  2. 修正搜索输入框的受控绑定
    原代码中输入框的value属性硬编码为字符串"filter",没有绑定store中的filter状态,导致输入框逻辑异常。调整为绑定store的filter值:
    <input
      type="text"
      value={this.props.CarStore.filter}
      onChange={this.filter.bind(this)}
    />
    
  3. 补全排序按钮的交互逻辑
    原代码的Sort按钮没有绑定点击事件,且一旦切换为排序状态就无法切回默认视图。调整为点击时切换排序状态:
    <button
      onClick={() => {
        this.props.CarStore.isSorted = !this.props.CarStore.isSorted
      }}
    >
      {this.props.CarStore.isSorted ? "取消A-Z排序" : "按A-Z排序"}
    </button>
    
  4. 增加空值兜底(推荐)
    在计算属性中增加判断,避免异常场景下再次触发filter方法报错:
    get filteredCars() {
        // 兜底判断:如果cars不是有效数组,直接返回空数组
        if (!Array.isArray(this.cars)) return [];
        let matchesFilter = new RegExp(this.filter, "i");
        return this.cars
            .filter((car) => car !== null)
            .filter((car) => !this.filter || matchesFilter.test(car.carname));
    }
    

补充说明:现有代码中MobX的makeObservable配置已经覆盖了所有用到的状态、计算属性和动作,这部分无需额外调整。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.25 21:54:11