请向我解释为什么我一直得到这个错误:ExpressionChangedAfterItHasBeenCheckedError:表达式已经改变后,它被检查。

显然,我只有在开发模式下才会遇到这种情况,在我的产品构建中不会出现这种情况,但这非常烦人,而且我根本不明白在我的开发环境中出现错误而不会在prod上显示的好处——可能是因为我缺乏理解。

通常,修复很简单,我只是把导致错误的代码包装在setTimeout中,就像这样:

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

或者使用如下构造函数强制检测更改:

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

但是为什么我总是遇到这个错误呢?我想要了解它,这样我就可以在将来避免这些俗套的修复。


当前回答

请遵循以下步骤:

1. 通过从@angular/core导入'ChangeDetectorRef'来使用它,如下所示:

import{ ChangeDetectorRef } from '@angular/core';

2. 在constructor()中实现,如下所示:

constructor(   private cdRef : ChangeDetectorRef  ) {}

3. 添加下面的方法到你的函数,你正在调用的事件,如点击按钮。它看起来是这样的:

functionName() {   
    yourCode;  
    //add this line to get rid of the error  
    this.cdRef.detectChanges();     
}

其他回答

我用rxjs解决了这个问题

import { startWith, tap, delay } from 'rxjs/operators';

// Data field used to populate on the html
dataSource: any;

....

ngAfterViewInit() {
  this.yourAsyncData.
      .pipe(
          startWith(null),
          delay(0),
          tap((res) => this.dataSource = res)
      ).subscribe();
}

我使用的是ng2-carouselamos (Angular 8和Bootstrap 4)

下面这些步骤解决了我的问题:

实现AfterViewChecked 添加构造函数(私有changeDetector: ChangeDetectorRef) {} 然后ngAfterViewChecked(){this.changeDetector.detectChanges();}

在我的例子中,我在运行测试时在规范文件中遇到了这个问题。

我必须把ngIf改成[hidden]

<app-loading *ngIf="isLoading"></app-loading>

to

<app-loading [hidden]="!isLoading"></app-loading>

解决方案…服务和rxjs…事件发射器和属性绑定都使用rxjs..你最好自己实现它,更多的控制,更容易调试。记住,事件发射器使用rxjs。简单地说,创建一个服务,并在一个可观察对象中,让每个组件订阅该观察对象,并根据需要传递新值或消耗值

我得到这个错误,因为我在模式中调度redux动作,当时模式还没有打开。我正在调度动作的瞬间模态组件接收输入。所以我把setTimeout放在那里,以确保模式是打开的,然后动作被分派。