ExpressionChangedAfterItHasBeenCheckedError 解释 [英] ExpressionChangedAfterItHasBeenCheckedError Explained

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

问题描述

请向我解释为什么我总是收到此错误:ExpressionChangedAfterItHasBeenCheckedError:表达式在检查后已更改.

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

显然,我只在开发模式下得到它,它不会发生在我的生产版本中,但这很烦人,而且我根本不明白在我的开发环境中出现不会出现的错误的好处在 prod 上——可能是因为我缺乏理解.

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();

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

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

推荐答案

了解了很多Angular Lifecycle Hooks 及其与变更检测的关系.

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天全站免登陆