简体   繁体   中英

Private fields turned on automatically readonly setters cannot assign

Currently I use Angular 13.1.1 version with Typescript 4.4.4

I have a strange problem, because the setters not working anymore in my model.

This is my example class:

export class Example extends SomeParent {

...
 private _isApproved: boolean;
...

constructor(...) {
   this._isApproved = true;  // this is fine
}

...

get isApproved(): boolean {
  return this._isApproved;
}

set isApproved(value: boolean) {
  this._isApproved = value;  // ERROR TypeError: Cannot assign to read only property '_isApproved' of object '[object Object]'
}

...

Is something changed in Typescript language or in Angular part? Its look like the private fields turned on automatically readonly without readonly keyword.

The error exist in all of my model classes!

How can I fixed that, because I don't want to turn my fields to public

I tried to cast any (this as any)._isApproved = value; but the problem still exist. Tried to cast all (this._isApproved as any) = value; the problem still exist, tried to rename, but the problem not fixed.

I tried to delete the node modules folder, with the package lock, and reinstall all the modules, not helped.

Someone faced this problem before?

All error:

core.mjs:6469 ERROR TypeError: Cannot assign to read only property '_isApproved' of object '[object Object]'
    at Example.set isApproved [as isApproved] (exammple.ts:53)
    at ExampleService.ModifyMemberStatus$ (example.service.ts:374)
    at example.effects.ts:274
    at source.subscribe._OperatorSubscriber__WEBPACK_IMPORTED_MODULE_1__.OperatorSubscriber.isComplete (switchMap.js:14)
    at OperatorSubscriber._next (OperatorSubscriber.js:9)
    at OperatorSubscriber.next (Subscriber.js:31)
    at map.js:7
    at OperatorSubscriber._next (OperatorSubscriber.js:9)
    at OperatorSubscriber.next (Subscriber.js:31)
    at filter.js:6

This is likely due to a wrong this scope: you are trying to set _isApproved property from outside the class this scope, and this is not allowed due to the private prefix.

You can try to use arrow functions:

setIsApproved = (value: boolean) => {
  this._isApproved = value;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM