typescript TypeError: Cannot add property 1, object is not extensible↵ at Array.push (< anonymous>)

1hdlvixo  于 2022-11-30  发布在  TypeScript
关注(0)|答案(4)|浏览(998)

我尝试将一些数据添加到数组中,但遇到不可扩展错误。
组件代码:

this._store.select(p => p.collection.workspaceCollectionPages).subscribe((data: CollectionPageDbModel[]) =>{
      if(data){
      return data.map((collectionPageDbModel)=> {

      this.collectionPages.push(collectionPageDbModel) //Getting error on this line while pushing

    });}

我的数据变量中有四个对象,我试图将它们推入collectionPages,但在推入时出现可扩展错误。


集合需要添加更多数据的页面数组


此数据需要推送
收藏页面数据库模型:

export class CollectionPageDbModel implements IDbModel {
  public id?: number;
  public collection_version_id: number;
  public user_id?: string;
  public name: string;
  public position?: number = 0;
  public contents: string;
  public created_at?: string;
  public updated_at?: string;
  public server_id?: any;

}

有人能帮我解决这个问题吗

uqcuzwp8

uqcuzwp81#

使用Object.assign方法复制对象,然后重试。

this.collectionPages = Object.assign([], this.collectionPages);
this.collectionPages.push(collectionPageDbModel);

ES6简化代码为:

this.collectionPages = [...this.collectionPages, collectionPageDbModel]
km0tfn4u

km0tfn4u2#

当我尝试将数据推送到数组时,也遇到了类似的错误警告。我的解决方案是使用spread操作符而不是push

let myarray: any = [];
const data = {
            answers: [],
            score: 24,
            ctime: '',
};
myarray = [...myarray, data]; // used this instead of push
mspsb9vt

mspsb9vt3#

Daniel提出的解决方案当然适用于这种情况。原因是每个JS对象都有对象描述符。你可以通过调用Object.getOwnPropertyDescriptors(obj)来检查它们,它也适用于数组,因为(几乎)所有东西都是对象。
问题中最可能使用的NGRX Store Selector通过使用Object.defineProperties(obj)修改对象描述符。这样做是为了防止Reducer之外的Store中的数据发生任何变化(Reducer也不会改变状态,只是创建一个新的状态)。
在一般情况下,你必须克隆你想要改变的对象:

import { cloneDeep } from 'lodash'

// ...

constructor(private store: Store<any>) {}

someMethod() {
  let someDataFromTheStore = cloneDeep(this.store.select(selectSomeData))
  someDataFromTheStore.myArray.push('...')
}

Object.assigncloneDeep都不会将描述符传输到新副本。
Object.getOwnPropertyDescriptors
Object.defineProperties

x6yk4ghg

x6yk4ghg4#

这一个工作,

if(data){
   const result = data.map((collectionPageDbModel)=> {
      this.collectionPages.push(collectionPageDbModel) //Getting error on this line while pushing
   });
   
   return result
   // incase of async call this one will work fine
   // return Promise.all(result)
}

相关问题