mobxjs / mobxjs/mobx

Inconsistent autorun behavior between first run and subsequent runs.

Open
#3,799 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

🐛 bug
Dominant language
TypeScript
Stars
28.2k
Forks
1.8k
Avg merge
1h 38m
Merged PRs (30d)
1

Description

Intended outcome:

I would have expected autorun to behave the same on its first run or its nth run, but it appears to do something different on the first run? For the following code I would have expected the autorun to loop until the observable value it's tracking stops changing.

test("autorun", () => {
  const o = mobx.observable.box(0);
  const seen: number[] = [];

  mobx.autorun(() => {
    seen.push(o.get());
    if (o.get() < 5) o.set(o.get() + 1);
  });
  expect(seen).toStrictEqual([0, 1, 2, 3, 4, 5]); // this assertion fails as "seen" is [0]
});

Actual outcome:
The following test case is the actual behavior.

test("autorun", () => {
  const o = mobx.observable.box(0);
  const seen: number[] = [];

  mobx.autorun(() => {
    seen.push(o.get());
    if (o.get() < 5) o.set(o.get() + 1);
  });
  // autorun doesn't continue to run even though a tracked observable value has changed
  expect(seen).toStrictEqual([0]); 

  // triggering the autorun again then causes it to loop (but it has "lost" the value 1)
  o.set(o.get() + 1);
  expect(seen).toStrictEqual([0, 2, 3, 4, 5]);
});

Versions
6.11.0

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reproducing the provided autorun test with MobX 6.11.0, then trace the autorun entry point and its scheduling behavior. Add or update coverage for the first-run case; done means the initial run observes [0, 1, 2, 3, 4, 5] without requiring a second observable update.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript, typescript
Domain
frontend
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
42/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.