Skip to content

NG0911: View has already been destroyed. #54527

Closed

Description

@dwilches

Which @angular/* package(s) are the source of the bug?

core

Is this a regression?

Yes

Description

I recently introduced to my app DestroyRef to replace @ngneat/until-destroy and I started getting an error in automated tests: NG0911: View has already been destroyed.

This issue doesn't manifest while users are interacting with the app, but when I'm testing the app via automated means (where I click very fast in buttons and components are created and destroyed too quickly).

The code where the exception happened is the following (I marked which one is line 76, the one mentioned in the stack trace):

    ngOnInit() {
        this.myHttpClient.getCharts()
            .then(allCharts => {
                this.allCharts = allCharts;

                this.myService.getPerms$("SOME_PERM")
                    .pipe(takeUntilDestroyed(this.destroyRef))
                    .subscribe(hasPerms => this.refreshChartDetails(hasPerms)); # line 76
            })
            .catch(error => this.myErrorService.showError(error));
    }

Please provide a link to a minimal reproduction of the bug

No response

Please provide the exception or error you saw

NG0911: View has already been destroyed.
    at storeLViewOnDestroy (core.mjs:2846:15)
    at NodeInjectorDestroyRef.onDestroy (core.mjs:14215:9)
    at Observable._subscribe (rxjs-interop.mjs:27:41)
    at Observable._trySubscribe (Observable.js:37:25)
    at Observable.js:31:30
    at errorContext (errorContext.js:19:9)
    at Observable.subscribe (Observable.js:22:21)
    at takeUntil.js:7:29
    at SafeSubscriber.<anonymous> (lift.js:10:28)
    at Observable.js:26:30
    at errorContext (errorContext.js:19:9)
    at AnonymousSubject.subscribe (Observable.js:22:21)
    at my-chart-component.component.ts:76:22
    at _ZoneDelegate.invoke (zone.js:368:26)
    at Object.onInvoke (core.mjs:14832:33)


### Please provide the environment you discovered this bug in (run `ng version`)

```true
Angular CLI: 17.1.2
Node: 18.13.0
Package Manager: npm 8.19.3
OS: linux x64

Angular: 17.1.2
... animations, cdk, cli, common, compiler, compiler-cli, core
... forms, material, material-moment-adapter, platform-browser
... platform-browser-dynamic, router

Package                         Version
---------------------------------------------------------
@angular-devkit/architect       0.1701.2
@angular-devkit/build-angular   17.1.2
@angular-devkit/core            17.1.2
@angular-devkit/schematics      17.1.2
@schematics/angular             17.1.2
rxjs                            7.8.1
typescript                      5.3.3
zone.js                         0.14.3

Anything else?

No response

Activity

  1. alxhub commented on Feb 20, 2024

    @alxhub
    Member

    Without a running reproduction it's difficult to be certain, but this seems like it's working as intended. By the time the Promise resolves, the containing component is already destroyed. The .then callback does .subscribe(), which subscribes through the takeUntilDestroyed operator, which tries to use the DestroyRef but it's too late - the component is already dead.

    The root cause here is the promise callback which executes the .subscribe unconditionally, even if the component is already destroyed.

  2. added
    needs reproduction
    area: core
    on Feb 20, 2024
  3. modified the milestone: Backlog on Feb 20, 2024
  4. dwilches commented on Feb 20, 2024

    @dwilches
    Author

    @alxhub Thanks, that explanation makes sense.

    I feel that Angular shouldn't be logging an error in that case though, as it's a normal use case, otherwise users will need to add a second validation before each "subscribe" that involves "takeUntilDestroyed" to make sure the component has not been destroyed already.

    Even if this is just a log, and not a real error, this causes trouble for tools that monitor the health of the application, for example we have failOnConsoleError in Cypress, so this makes the tests fail from time to time (as it acts as a race-condition). Similarly, error reporting tools like Rollbar would need adjustment to learn to ignore errors if this happens in production.

  5. sysmat commented on Feb 29, 2024

    @sysmat

    yes, have the same problem, but in runtime

  6. sysmat commented on Feb 29, 2024

    @sysmat

    I moved to old way OnDestroy hook and takeUntil and error is gone

  7. sysmat commented on Mar 1, 2024

    @sysmat
    • je for monitoring I use sentry and if not sentry error report I would probably not now for error
    • NG0911 no documentation
  8. DmSor commented on Mar 6, 2024

    @DmSor

    It would be convenient if DestroyRef had a destroyed flag.
    It would be possible to check before creating a subscription.

    abstract class DestroyRef {
      abstract onDestroy(callback: () => void): () => void;
      abstract readonly destroyed: boolean;
    }
  9. alexkunin commented on Mar 16, 2024

    @alexkunin

    [...] this seems like it's working as intended. By the time the Promise resolves, the containing component is already destroyed. The .then callback does .subscribe(), which subscribes through the takeUntilDestroyed operator, which tries to use the DestroyRef but it's too late - the component is already dead.

    I tend to agree with @alxhub, things work as intended. It's not totally unreasonable to not log the error in this particular case, but generally I'd rather know if my code accesses resources that have been already freed.

    Maybe it would be better to fix the code snippet listed above, instead of extending Angular responsibility with detecting right or wrong cases of "View has already been destroyed" error.

    For example, that code snippet uses three somewhat orthogonal concepts:

    • a class field that holds value -- just a plain value, nothing reactive here
    • a promise -- which loads data for that value
    • an observable -- that does some additional processing after promise is complete

    What if we rewrite code like this:

    ngOnInit() {
        from(this.myHttpClient.getCharts()).pipe(
            catchError(error => this.myErrorService.showError(error)),
            tap(allCharts => this.allCharts = allCharts),
            switchMap(() => this.myService.getPerms$("SOME_PERM")),
            tap(() => hasPerms => this.refreshChartDetails(hasPerms)),
            takeUntilDestroyed(this.destroyRef),
        ).subscribe();
    }

    So, now:

    • we have single flow of events/data
    • everything is bound during component initialization
    • destroying component early will also cancel promise in progress

    Also, I'd suggest to rewrite code to be more reactive, e.g.:

    class Component {
      readonly allCharts$ = defer(() => this.myHttpClient.getCharts());
    }

    But I see too little context to be sure that's viable in your case.

  10. smleake commented on Apr 9, 2024

    @smleake

    We've recently started experiencing this issue within our codebase as well and have identified that it's coming from our usages of takeUntilDestroyed. We have found that a likely significant contributor to the errors is an Observable that shouldn't be using the operator in the first place (because it's within a hot function that get's invoked multiple times throughout the life of the component, take(1) would likely be a better fit). Just so I'm absolutely clear, this error occurs whenever we try to subscribe to an Observable utilizing takeUntilDestroyed but the view has been destroyed already. Is that a fair assumption? Thanks guys, appreciate your time!

  11. CosmoFruit commented on Apr 23, 2024

    @CosmoFruit
  12. waterplea commented on Apr 24, 2024

    @waterplea
    Contributor

    I think if we use takeUntilDestroyed on an already destroyed view it should immediately terminate the subscription, rather than throw an error.

  13. 31 remaining items

  14. arturovt commented on Apr 2, 2025

    @arturovt
    Contributor

    @dwilches you can close the issue since the fix has been merged (arturovt@af55238).

  15. canutoalex commented on Apr 7, 2025

    @canutoalex

    @dwilches @thePunderWoman Any chance on making this available not only in major, but in a next 19.x version? We are experiencing it right now and we would like to avoid workarounds or reverting to OnDestroy / takeUntil in a lot of places.

  16. angular-automatic-lock-bot commented on May 8, 2025

    @angular-automatic-lock-bot

    This issue has been automatically locked due to inactivity.
    Please file a new issue if you are encountering a similar or related problem.

    Read more about our automatic conversation locking policy.

    This action has been performed automatically by a bot.

  17. locked and limited conversation to collaborators on May 8, 2025
  18. JeanMeche commented on May 22, 2025

    @JeanMeche
    Member

    I'll re-open this issue for tracking purposes,

    We decided to revert #58008, because it introduces a semi-synchronous behaviour that we'd like to avoid in the framework.

    For those interested, a short read on mixing sync & async callbacks .

  19. added 4 commits that reference this issue on May 27, 2025
    2aae3ef
    bf82af7
    1d58b57
    6ab7d1c
  20. added a commit that references this issue on Jun 4, 2025
    8c60cbf
  21. added a commit that references this issue on Jun 4, 2025
    2bd3a43
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area: corecore: rxjs interop

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions