填寫這份《一分鐘調查》,幫我們(開發組)做得更好!去填寫Home

NG0100: Expression has changed after it was checked
表示式在檢查過之後又改變了

說明

Description

當變更檢測完成後又更改了表示式值時,Angular 就會丟擲 ExpressionChangedAfterItHasBeenCheckedError 錯誤。Angular 只會在開發模式下丟擲此錯誤。

Angular throws an ExpressionChangedAfterItHasBeenCheckedError when an expression value has been changed after change detection has completed. Angular only throws this error in development mode.

在開發模式下,Angular 在每次變更檢測執行後都會執行一次附加檢查,以確保繫結沒有更改。這會在檢視處於不一致狀態時捕獲錯誤。例如,如果某個方法或 getter 每次被呼叫時都會返回一個不同的值,或者某個子元件更改了其父元件上的值,就可能會發生這種情況。如果發生這兩種情況,則表明變更檢測是不穩定的。Angular 會丟擲錯誤以確保資料始終正確地反映在檢視中,從而防止 UI 行為不穩定或可能的無限迴圈。

In dev mode, Angular performs an additional check after each change detection run, to ensure the bindings haven’t changed. This catches errors where the view is left in an inconsistent state. This can occur, for example, if a method or getter returns a different value each time it is called, or if a child component changes values on its parent. If either of these occur, this is a sign that change detection is not stabilized. Angular throws the error to ensure data is always reflected correctly in the view, which prevents erratic UI behavior or a possible infinite loop.

當你添加了範本表示式或開始實現生命週期掛鉤(例如 ngAfterViewInitngOnChanges)時,容易發生此錯誤。在處理載入狀態和非同步操作,或者子元件更改其父元件中的繫結時,這也很常見。

This error commonly occurs when you’ve added template expressions or begun to implement lifecycle hooks like ngAfterViewInit or ngOnChanges. It is also common when dealing with loading status and asynchronous operations, or a child component changes its parent bindings.


如何排除本錯誤

Debugging the error

CLI 產生的原始碼對映在除錯時非常有用。向上瀏覽呼叫棧,直到找到錯誤中所顯示的、值已更改的範本表示式。

The source maps generated by the CLI are very useful when debugging. Navigate up the call stack until you find a template expression where the value displayed in the error has changed.

執行變更檢測後,請確保範本中的繫結沒有更改。這通常意味著需要針對你的用例進行重構以使用正確的元件生命週期鉤子。 如果此問題存在於 ngAfterViewInit 中,建議的解決方案是使用建構函式或 ngOnInit 來設定初始值,或者使用 ngAfterContentInit 做其他值的繫結。

Ensure that there are no changes to the bindings in the template after change detection is run. This often means refactoring to use the correct component lifecycle hook for your use case. If the issue exists within ngAfterViewInit, the recommended solution is to use a constructor or ngOnInit to set initial values, or use ngAfterContentInit for other value bindings.

如果要繫結到檢視中的方法,請確保呼叫不會更新範本中的任何其他繫結。

If you are binding to methods in the view, ensure that the invocation does not update any of the other bindings in the template.

“你需要了解的關於 “ExpressionChangedAfterItHasBeenCheckedError” 錯誤的一切”中學習為什麼該解決方案更合適,以及在 “Angular 除錯:檢查後表示式已更改”的簡單說明(和修復)中瞭解為什麼這樣做會有用。

Read more about which solution is right for you in 'Everything you need to know about the "ExpressionChangedAfterItHasBeenCheckedError" error' and why this is useful at 'Angular Debugging "Expression has changed after it was checked": Simple Explanation (and Fix)'.