首页 > 解决方案 > TypeError:无法添加属性 newField,对象不可扩展

问题描述

我收到错误

TypeError:无法添加属性 newField,对象不可扩展

虽然添加任何新键或更改任何值都不会发生,但不知道出了什么问题。

 dynamicFilter;

 public ionViewWillEnter() {
    this.commonservice.showLoading();
    this.store.dispatch(activeBookingActions.getBookingFiltersRequest());
    this.bookingFilterSubscription = this.store.pipe(select(selectActiveBookingData)).subscribe(response => {
      this.commonservice.hideLoading();
      if (response.bookingdata && response.bookingdata.filterlist && response.bookingdata.filterlist.data && (response.bookingdata.filterlist.data.action === 'bookingFilters')) {
        this.commonservice.hideLoading();
        this.filterList = response.bookingdata.filterlist.data.list;
        this.sortingList = this.filterList.sorting;
        this.dynamicFilter = [...this.filterList.filter];
        console.log(this.dynamicFilter);

         this.dynamicFilter.forEach((x) => {
           if (x.design_type == 'checkbox') {
             x.design_type = 'sadas';     // this line giving error
           }
         });
      }
    });
  }

试过
https://stackoverflow.com/a/49022130/12917651

没有运气。

标签: angulartypescript

解决方案


我认为您从无法直接修改数据的商店或 NgRx 获取数据(ngrx-store-freeze)。

尝试创建数组中每个项目的对象的副本。

this.dynamicFilter = this.filterList.filter.map(data => ({ ...data }));
        console.log(this.dynamicFilter);

         this.dynamicFilter.forEach((x) => {
           if (x.design_type == 'checkbox') {
             x.design_type = 'sadas';     // this line giving error
           }
         });

Map 将不可变地转换数组,并且数组中的每个对象都使用扩展运算符 (...) 传播到内存中的新位置。


推荐阅读