ERROR TypeError: Cannot add property x, object is not extensible Angular Subscriber

ctrl/m
0



The JavaScript exception "can't define property "x": "obj" is not extensible" occurs when 
Object.preventExtensions() marked an object as no longer extensible, so that it will never have properties beyond the ones it had at the time it was marked as non-extensible.

According to this reference


Before:

private _getDummy(): void {
this.dummy$.subscribe((data: Array<DummyModel>) => {
this.obj = data;
});

} 

The JavaScript error "can't define property "x": "obj" is not extensible" occurs when an object is

marked as not extensible, meaning that it cannot have new properties beyond the ones it

already has. It seems that the value passed from the subscriber returns a copy with the

preventExtension property attached to it. To fix this issue, the code can be modified to create

a shallow copy of the payload using JSON.stringify() and JSON.parse() methods.


The modified code would look like this:

After

private _getDummy(): void {
this.dummy$.subscribe((data: Array<DummyModel>) => {
this.obj = this._returnShallowCopy(data);
});
}

private _returnShallowCopy(payload: any): any {
return JSON.parse(JSON.stringify(payload));
}


This way, the preventExtension property is not included in the copied object, and the error is
avoided.
Tags:

Post a Comment

0Comments

Post a Comment (0)