Skip to content

Use WeakRef for observers#4622

Open
bjb568 wants to merge 4 commits intomobxjs:mainfrom
bjb568:weakref
Open

Use WeakRef for observers#4622
bjb568 wants to merge 4 commits intomobxjs:mainfrom
bjb568:weakref

Conversation

@bjb568
Copy link
Copy Markdown

@bjb568 bjb568 commented Mar 10, 2026

This PR changes the observers of an observable to use a weak reference, which allows computed values with the keepAlive option to be garbage collected.

In the following code, without this PR, memory usage grows without bound. With this PR, buffer is able to be disposed.

import { observable, computed } from "mobx";

const box = observable.box(1);

setInterval(() => {
  const megabytes = performance.memory.usedJSHeapSize / 1e6;
  console.log(`${megabytes.toFixed(2)} MB used.`);

  const buffer = observable.box(new ArrayBuffer(100 * 1e6));
  computed(() => buffer.get().byteLength * box.get(), {
    keepAlive: true,
  }).get();
}, 1000);

With the following code, since it is creating a reaction, it shouldn't be disposed. This is accomplished by having a globalState.activeReactions set to prevent garbage collection. Both with and without this PR, memory will grow without bound (autoruns still need to be disposed of).

import { observable, computed } from "mobx";

const box = observable.box(1);

setInterval(() => {
  const megabytes = performance.memory.usedJSHeapSize / 1e6;
  console.log(`${megabytes.toFixed(2)} MB used.`);

  const buffer = observable.box(new ArrayBuffer(100 * 1e6));
  autorun(() => buffer.get().byteLength * box.get());
}, 1000);

Since this PR deals with garbage collection, it's difficult to write unit tests verifying this behavior, so the verification was done in a browser.

Code change checklist

  • Added/updated unit tests
  • Updated /docs. For new functionality, at least API.md should be updated
  • Verified that there is no significant performance drop (yarn mobx test:performance)

@changeset-bot
Copy link
Copy Markdown

changeset-bot bot commented Mar 10, 2026

🦋 Changeset detected

Latest commit: b61de45

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package
Name Type
mobx Minor

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

bjb568 added 3 commits March 9, 2026 21:00
This naming supports changing it in the future to exclude certain reactions if WeakRef reactions are ever added.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant