Angular2/Typescript/ngRx - TypeError: Cannot assign to read only property of object

11,341

Solution 1

Credits to Ryan Q:

As Ryan commented I was using ngRx in my app and I was indeed passing this.selectedDate object through an action into the store and hence I was not able to modify the object that is stored in the State.

One way to resolve this is pass a new object reference and this should resolve the issue:

this.store.dispatch(new settime.DateChangeAction(Object.assign({}, this.selectedDate)));

Solution 2

@vikas' answer put me on the right track to solve a similar issue.

I'm trying to handle an upload, where I want to display the progress:
- From the UploadComponent, I emit an event to the parent
- The parent dispatch an action to the store
- An effect catches the action, call the service to upload the file (which returns an array with two observables: progress$ and result$)
- The effect dispatch an HttpProgress action which contains the observable

And at this point I had a similar issue. After digging into store freeze code, a coworker and I found out that it also deep freeze the action.payload. And thus, passing an observable results into an error as observable state is mutated internally.

I'm not using the payload to keep it into the store, just so I can register to actions$ within my component so here it doesn't matter if I pass a mutable object into the payload. To avoid that error, I just wrapped the observable into a function as deep freeze do not freeze functions.

Share:
11,341
Vik
Author by

Vik

Updated on June 09, 2022

Comments

  • Vik
    Vik almost 2 years

    In the constructor I do something like this

    selectedDate: Object;
    // construtor
    this.selectedDate = {};
    this.selectedDate['date'] = new Date();
    this.selectedDate['pristine'] = new Date();
    

    In another function which gets called on a button click I do the following:

    this.selectedDate['date'] = new Date(this.selectedDate['pristine']);
    

    And I get the following error:

    TypeError: Cannot assign to read only property 'date' of object '[object Object]'