ExpressionChangedAfterItHasBeenCheckedError说明 [英] ExpressionChangedAfterItHasBeenCheckedError Explained

查看:127
本文介绍了ExpressionChangedAfterItHasBeenCheckedError说明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请向我解释为什么我不断出现此错误:ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked.

Please explain to me why I keep getting this error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked.

很明显,我只在开发人员模式下获得它,这在我的生产版本中不会发生,但是这很烦人,我根本不理解在我的开发人员环境中出现错误不会显示的好处可能是因为我缺乏了解.

Obviously, I only get it in dev mode, it doesn't happen on my production build, but it's very annoying and I simply don't understand the benefits of having an error in my dev environment that won't show up on prod --probably because of my lack of understanding.

通常,此修复很容易,我只是将导致代码的错误包装在setTimeout中,如下所示:

Usually, the fix is easy enough, I just wrap the error causing code in a setTimeout like this:

setTimeout(()=> {
    this.isLoading = true;
}, 0);

或者使用如下构造函数强制检测更改:constructor(private cd: ChangeDetectorRef) {}:

Or force detect changes with a constructor like this: constructor(private cd: ChangeDetectorRef) {}:

this.isLoading = true;
this.cd.detectChanges();

但是为什么我经常遇到这个错误?我想了解它,以便将来避免这些hacky修复程序.

But why do I constantly run into this error? I want to understand it so I can avoid these hacky fixes in the future.

推荐答案

一旦我理解了角生命周期挂钩及其与变更检测的关系.

A lot of understanding came once I understood the Angular Lifecycle Hooks and their relationship with change detection.

我试图让Angular更新绑定到元素*ngIf的全局标志,并且试图在另一个组件的ngOnInit()生命周期挂钩内更改该标志.

I was trying to get Angular to update a global flag bound to the *ngIf of an element, and I was trying to change that flag inside of the ngOnInit() life cycle hook of another component.

根据文档,在Angular已经检测到更改后调用此方法:

According to the documentation, this method is called after Angular has already detected changes:

在第一个ngOnChanges()之后调用一次.

Called once, after the first ngOnChanges().

因此,更新ngOnChanges()内部的标志不会启动更改检测.然后,一旦自然而然地再次触发了更改检测,该标志的值就会更改,并引发错误.

So updating the flag inside of ngOnChanges() won't initiate change detection. Then, once change detection has naturally triggered again, the flag's value has changed and the error is thrown.

就我而言,我对此进行了更改:

In my case, I changed this:

constructor(private globalEventsService: GlobalEventsService) {

}

ngOnInit() {
    this.globalEventsService.showCheckoutHeader = true;
}

对此:

constructor(private globalEventsService: GlobalEventsService) {
    this.globalEventsService.showCheckoutHeader = true;
}

ngOnInit() {

}

它解决了问题:)

这篇关于ExpressionChangedAfterItHasBeenCheckedError说明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆