Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 39 ยท Tracked State and Reactivity

Reactivity Pitfalls and Debugging

Diagnose the common Ember reactivity bugs: missing @tracked, mutation, backtracking rerender assertions, stale copies of arguments, lost this, and async races.

Autotracking removes most reactivity bugs, but a handful of mistakes remain, and they all look alike from the outside: "I changed the data and the screen did not update" or "Ember threw a scary assertion". This lesson lists the usual suspects with the symptom, the cause and the fix, then shows a runnable model of the most confusing one: the backtracking re-render error.

Real Ember vs stand-in. File-named blocks are real Ember code (read-only). Runnable blocks are plain JavaScript models of the behavior.

A checklist for "the screen did not update"

Walk through this list in order. It finds the cause nearly every time.

  1. Is the field @tracked (or inside a tracked collection, or an argument)?
  2. Did you assign to it, or did you mutate something inside it?
  3. Is the value read in the template or in a getter the template reads?
  4. Is this correct inside the function that changes it (@action)?
  5. Is a stale copy of the data being shown instead of the source?

Pitfall 1: a missing @tracked

JavaScript
export default class Greeting extends Component {
  name = 'Ada'; // forgot @tracked

  @action rename() {
    this.name = 'Grace'; // changes, but the template never learns
  }
}

Fix: @tracked name = 'Ada';. If a value never changes after creation, it needs no tracking; if it can change and is displayed, it does.

Pitfall 2: mutation instead of assignment

Changing this.items.push(x) or this.user.name = 'x' leaves the tracked field's reference unchanged. Replace the value, or use tracked collections.

Pitfall 3: a lost this

JavaScript
export default class Counter extends Component {
  @tracked count = 0;

  increment() {          // no @action
    this.count++;        // `this` is not the component when called from the event
  }

  <template>
    <button {{on "click" this.increment}}>+</button>
  </template>
}

An event listener calls the function without the component as this, so this.count is undefined or throws. Fix: decorate with @action, which binds the method. Methods you call yourself from other methods (this.helper()) do not need it; methods you hand to the template as callbacks do.

Pitfall 4: copying arguments

JavaScript
export default class Title extends Component {
  @tracked text = this.args.title; // copied once, then stale
}

If the parent changes @title, text keeps the old value. Read this.args.title directly, or derive with a getter. If you really need an editable local copy (a form that starts from the argument), copy it deliberately, and name it so: draftTitle.

Pitfall 5: a stale closure over old data

A callback created once and used later can see old values if it captured a copy:

JavaScript
const total = this.total;            // number captured now
setTimeout(() => alert(total), 5000); // shows the old total

Read through this at the time of use (alert(this.total)) when you want the latest value.

Pitfall 6: async races

If a user types quickly and each keystroke starts a request, responses can come back out of order and an old answer can overwrite a new one. Remember which request is current:

JavaScript
@tracked results = [];
#latest = 0;

@action async search(event) {
  const ticket = ++this.#latest;
  const found = await this.api.search(event.target.value);
  if (ticket === this.#latest) {
    this.results = found; // only the newest request may write
  }
}

The stand-in below plays that out with fake delays so you can see the race and the fix.

JS Stand-in: a search race and its fix

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The naive version ends up showing results for the older query em because its slow reply arrived last. The ticket check fixes it.

The backtracking re-render assertion

The most intimidating message in Ember reads something like:

You attempted to update total on Cart, but it had already been used previously in the same computation. Attempting to update a value after using it in a computation can cause logical errors, infinite revalidation bugs, and performance issues, and is not supported.

It means: during a single render, something read a tracked value, and later in the same render something changed it. The part of the page that already used the old value is now out of date, and Ember refuses to loop. It is almost always one of these:

  • A getter that sets tracked state (get x() { this.y = 1; ... }).
  • A child component that changes a tracked value in a service or in its parent during its own construction or render, after the parent already displayed it.
  • An {{ }} helper with side effects.
sequenceDiagram
  participant T as Template
  participant P as Parent value
  participant C as Child (during render)
  T->>P: read count (shows 0)
  T->>C: render child
  C->>P: set count = 1 (during render)
  Note over T,P: Ember: count was already used in this render

The parent already printed 0; a later write in the same render would require printing it again.

The model below detects the same condition: a value read during a render and written later in that render.

JS Stand-in: detecting a backtracking write

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Fixing backtracking errors

  • Derive instead of set. If a getter wanted to set y from x, make y a getter itself.
  • Move the write to an event or lifecycle moment. Change state in an action (a click, a submit), in a route hook, or after a resource loads, not inside a getter or helper.
  • Do it earlier. Initialize the value in the constructor or model hook, before anything reads it.
  • Defer when you truly must. next/schedule from @ember/runloop or an {{on}}/modifier callback runs after the render. Treat this as a last resort; it usually means the data flow can be reorganized.

Do not silence the assertion by catching it or by clever re-ordering. It is pointing at a real inconsistency: the screen could show two different values for the same state.

Debugging tools

  • Ember Inspector (browser extension): inspect the component tree, see current argument and tracked values, view the render performance and the data store.
  • {{log this.value}} in a template prints a value on every render (remove it afterwards).
  • {{debugger}} stops execution in the browser inside the template context.
  • Temporary logging: a console.log inside a getter shows how often it runs and with what values.
  • Tests: a failing rendering test that changes state and asserts the DOM is the best reproduction. See Rendering Tests.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A button handler method increments this.count but throws "cannot read properties of undefined". What is the most likely fix?

    An unbound method loses this when the browser calls it from an event. @action binds it.
  2. 2. What triggers the backtracking re-render assertion?

    The rendered output already used the old value, so changing it mid-render would leave the page inconsistent. Ember refuses.
  3. 3. A component does @tracked text = this.args.title. The parent changes @title but the child still shows the old text. Why?

    Initializers run once at creation. Reading the argument at render time keeps the display current.
  4. 4. Fast typing sends several searches and an older response overwrites newer results. What is a standard fix?

    Ignoring responses that are not from the newest request prevents out-of-order replies from winning.

Summary

  • Check in order: tracked? assigned? read in a template? bound with @action? stale copy?
  • Mutating inside a tracked field, copying this.args once, and forgetting @action cause most "no update" bugs.
  • The backtracking assertion means a value was changed after being used in the same render; derive, move the write to an event, or initialize earlier.
  • Guard async code against out-of-order responses.
  • Use Ember Inspector, {{log}} and rendering tests to find problems quickly.

Next: Testing Ember Apps