Angular2 - Error: The view has been destroyed and cannot be updated: detectChanges

My application keeps encountering this persistent error:

extensions::uncaught_exception_handler:8 Error in event handler for runtime.onMessage: Attempt to use a destroyed view: detectChanges
at ViewDestroyedException.BaseException [as constructor] (chrome-extension://npblbblmbmcjbldhcneoocaobkkicbno/node_modules/@angular/core/core.umd.js:3776:27)
at new ViewDestroyedException (chrome-extension://npblbblmbmcjbldhcneoocaobkkicbno/node_modules/@angular/core/core.umd.js:6957:20)
at DebugAppView.AppView.throwDestroyedError (chrome-extension://npblbblmbmcjbldhcneoocaobkkicbno/node_modules/@angular/core/core.umd.js:10041:76)
at DebugAppView.AppView.detectChanges (chrome-extension://npblbblmbmcjbldhcneoocaobkkicbno/node_modules/@angular/core/core.umd.js:9994:22)
at DebugAppView.detectChanges (chrome-extension://npblbblmbmcjbldhcneoocaobkkicbno/node_modules/@angular/core/core.umd.js:10084:48)
at ViewRef_.detectChanges (chrome-extension://npblbblmbmcjbldhcneoocaobkkicbno/node_modules/@angular/core/core.umd.js:9397:69)
at SafeSubscriber.eval [as _next] (chrome-extension://npblbblmbmcjbldhcneoocaobkkicbno/scripts/components/product-card.component.js:63:54)
at SafeSubscriber.__tryOrUnsub (chrome-extension://npblbblmbmcjbldhcneoocaobkkicbno/node_modules/rxjs/Subject/../bundles/Rx.umd.js:1408:16)
at SafeSubscriber.next (chrome-extension://npblbblmbmcjbldhcneoocaobkkicbn...

Whenever I call detectChanges on a specific component's ChangeDetectorReference:

this._changeDetectorRef.detectChanges();

I found a similar inquiry on Stack Overflow:

What is a dehydrated detector and how am I using one here?

As well as related discussions on GitHub:

https://github.com/angular/angular/issues/6786 https://github.com/angular/angular/issues/6786#issuecomment-185429140

This prompted me to try calling detectChanges differently:

setTimeout( () => this._changeDetectorRef.detectChanges(), 10);

Although this modification resulted in a different error message:

zone.js:260 Uncaught Attempt to use a destroyed view: detectChanges
Zone.runTask @ zone.js:260
ZoneTask.invoke @ zone.js:423

The issue persists, despite the adjustment made with setTimeout. Although it no longer breaks my application (as before), I remain eager to resolve it.

The reason I invoke detectChanges() is due to background processes altering the application state (not due to user input). The component remains active and retains its style in response to these background events.

Answer №1

Ensure to include this code snippet within the constructor of your class:

setTimeout( () => this._changeDetectorRef.markForCheck(), 10);

Also, remember to add the following line in @Component:

changeDetection: ChangeDetectionStrategy.OnPush,

Answer №2

My issue arose when a subscribe() function was attempting to run its completion code after the view had already been altered.

...
.then(response => {
    ...
    scope.cdr.detectChanges();
});
...

This problem would occur if I rapidly switched views or experienced slow internet connection.


To solve this, I introduced a boolean that is initially set to true upon view creation:

view_active: Boolean = true

Then, when the view is removed, it is changed to false:

ngOnDestroy() {
    this.view_active = false
}

I then added a check to ensure that detectChanges() is only called if the view is still active:

...
.then(response => {
    ...
    if(scope.view_active) {
        scope.cdr.detectChanges();
    }
});
...

Answer №3

Alternatively, you have the option to utilize the following code snippet:

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

setTimeout(() => {
  if(!(this.changeDetectorRef as ViewRef).destroyed) {
    this._changeDetectorRef.detectChanges();
  }
}, 10);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Pass JSON data from Angular service to component

I have encountered a challenge while trying to pass JSON data from my API service to a component without directly subscribing in the component. The issue arises when attempting to access the data outside of the subscription block, as it returns something u ...

Troubleshooting JavaScript in Internet Explorer 9

Currently, I am encountering an issue while attempting to debug JavaScript .js files in my Solution using Visual Studio 2010 and IE 9. Despite placing breakpoints in the files, I am unable to debug successfully. I have attempted various troubleshooting ste ...

Is there a method to track the progress of webpage loading?

I am working on a website built with static HTML pages. My goal is to implement a full-screen loading status complete with a progress bar that indicates the page's load progress, including all images and external assets. Once the page has fully loaded ...

How can I transfer information from an HTML file (using the ejs template engine) to Node.js?

Currently, I am working on my own project using a combination of Node.Js (Express), MongoDB, JavaScript/jQuery, and HTML with EJS as the template engine. So far, I have some understanding of how to send data from the Node.js router to views and how to sen ...

What could be the reason for the next.js Script tag not loading the third-party script when using the beforeInteractive strategy?

I have been trying to understand how the next.js Script tag with the beforeInteractive strategy works. I am currently testing it with lodash, but I keep encountering a ReferenceError: _ is not defined. I was under the impression that when a script is loade ...

Deciphering the Cause of mapStateToPropsCall in Redux and React

When handling an unsuccessful http call resulting in an error message being displayed, I encounter subsequent state changes triggering multiple render calls. Is there a technique to identify the cause of these state changes and mapStateToProps calls? Alter ...

Updating the titles of Bootstrap 4 Switches on the fly

Currently utilizing Bootstrap 4 Toggle on my website, I'm struggling to figure out how to dynamically modify the labels on the toggles at runtime. My objective is to implement a toggle-switch that, once activated, displays a countdown indicating the ...

Issue with React and JavaScript: Object is displayed on the console briefly before disappearing

I am having an issue with my sign up page where the console log of the two fields disappears after a second. I would appreciate any assistance on this matter. Below is the code for the sign-up form: export default function SignUp() { const [firstNam ...

The Vuex this.$store is not defined in the "mounted" lifecycle hook of the component

Currently in the process of integrating Paypal into my Vue project, following the official documentation and copying the necessary code from here. Successfully rendered the Paypal button, completed the transaction, and obtained an orderID. However, encount ...

Determining the type of index to use for an interface

Imagine having an interface called Animal, with some general properties, and then either be a cat or a dog with corresponding properties. interface Dog { dog: { sound: string; } } interface Cat { cat: { lives: number; } } type CatOrDog = Cat | D ...

Issue encountered when attempting to import a module within the ionic framework

I encountered an issue in my project (built with the ionic-framework 3) where I included the following line to import the dialogflow module: const dialogflow = require('dialogflow'); However, when compiling, it resulted in the error message: ...

Is the unit test for attribute failure specific to running it on only one node?

I am currently using Enzyme and Jest to verify the presence of an id attribute in a dropdown list. import React from "react"; import { mount } from "enzyme"; import ListPicker from './ListPicker.js' describe("ListPicker", () => { let props ...

An easy way to incorporate a fade-in effect for every word in a text

I am trying to make the text "Eat. Sleep. Repeat." slide up and fade in one word at a time. I have experimented with various methods like anime.js, keyframes, and adding css classes, but so far none of them have worked for me. Here is the code I currently ...

Hide the div when hovering occurs

I need a way to hide the 'sample' div when hovering over it and then show it again when the mouse moves away $('.secmenu').hover(function() { $('.sample').css('opacity', '0'); if ($('.secmenu&a ...

Tips for selecting objects based on property in Typescript?

Consider this scenario: import { Action, AnyAction } from 'redux'; // interface Action<Type> { type: Type } and type AnyAction = Action<any> export type FilterActionByType< A extends AnyAction, ActionType extends string > ...

The Vue v-on:click event listener seems to be unresponsive when applied to a

I've been attempting to utilize the on-click directive within a component, but for some reason, it doesn't seem to be functioning. Whenever I click on the component, nothing happens, even though I should see 'test clicked' in the consol ...

The height of the iframe with the id 'iframe' is not functioning as expected

I am trying to set the iFrame's height to 80% and have an advertisement take up the remaining 20%. Code <!DOCTYPE html> <html lang="en"> <head> </head> <body> <iframe id="iframe" src="xxxxxx" style="border: ...

The significance of the "$=" or "?=" symbols in lit-element illustrations

I'm struggling to comprehend the purpose of ?= or $= in these two instances: First Example: Lit-Element README <div id="box" class$="${this.uppercase ? 'uppercase' : ''}"> <slot>Hello World</slot> </div> ...

Ways to verify the timeframe between two specific dates

Having two distinctive arrays: accomodation: [ { id: 1, name: "Senator Hotel Fnideq", address: "Route de Ceuta, 93100 Fnidek, Morocco", checkin: "September 1", fullCheckinDate: "2021-09-01", ...

Can Angular Material Tabs be customized to have a different style?

I need help styling my mat-tabs to achieve a specific look. Here is the design I am trying to replicate: https://i.stack.imgur.com/tg6XC.png https://i.stack.imgur.com/tth0z.png However, I'm encountering an issue where the white border under the curr ...