[英]Angular2/Typescript/ngRx - TypeError: Cannot assign to read only property of object
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]' TypeError:无法分配给对象'[object Object]'的只读属性'date'
Credits to Ryan Q: 致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. 正如Ryan评论的那样,我在我的应用程序中使用了ngRx,并且我确实通过一个动作将this.selectedDate对象传递到了商店,因此我无法修改存储在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)));
@vikas' answer put me on the right track to solve a similar issue. @vikas的回答让我走上了解决类似问题的正确轨道。
I'm trying to handle an upload, where I want to display the progress: 我正在尝试处理上传,我想在其中显示进度:
- From the UploadComponent
, I emit an event to the parent - 从UploadComponent
,我向父母发出一个事件
- 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$
) - 一个效果捕获动作,调用服务上传文件(返回一个包含两个observable的数组: progress$
和result$
)
- The effect dispatch an HttpProgress
action which contains the observable - 效果调度包含observable的HttpProgress
动作
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
. 在深入了解商店冻结代码后,我和同事发现它还深度冻结了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. 为了避免这个错误,我只是将observable包装成函数,因为深度冻结不会冻结函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.