Skip to content

on_mount inside rx.foreach that uses the loop variable crashes the page #7791

Closed

Description

@FarhanAliRaza

Describe the bug

An on_mount (or on_unmount) event on a component inside rx.foreach that uses the loop variable crashes the page with a ReferenceError.

To Reproduce

import reflex as rx


class S(rx.State):
    items: list[str] = ["a", "b"]
    log: list[str] = []

    @rx.event
    def seen(self, x: str):
        self.log.append(f"seen:{x}")


def index():
    return rx.box(
        rx.foreach(S.items, lambda x: rx.text(x, on_mount=S.seen(x))),
        rx.text(S.log.join(","), id="log"),
    )


app = rx.App()
app.add_page(index)

Run with the default config and open the page.

Actual behavior

The page does not render. The error boundary shows:

An error occurred while rendering this page.
ReferenceError: x_rx_state_ is not defined

Expected behavior

The page renders, and each item fires its own event: seen:a, seen:b.

Cause

The lifecycle event compiles to a useEffect hook. The whole rx.foreach block becomes one memo component, and the hook goes to the top of that component, outside the loop. The loop variable exists only inside the .map() callback below it. Generated code (.web/app_components/...):

const Foreach_comp_... = memo(({children}) => {
  const s = useStateContext("...")
  useEffect(() => {
    ((...args) => (addEvents([(ReflexEvent("...seen", ({ ["x"] : x_rx_state_ }), ({ })))], args, ({ }))))()
    return () => {}
  }, []);
  return (
    Array.prototype.map.call(s.items_rx_state_ ?? [], ((x_rx_state_, index_...) => (jsx(RadixThemesText, {as:"p", key:index_...}, x_rx_state_))))
  )
});

For the same reason, an on_mount in rx.foreach that does not use the loop variable does not crash, but it fires once for the whole list, not once per item.

Specifics

  • Reflex: main at 58e7128, default config (no react_compiler), reflex run --env prod
  • Browser: Chromium
  • OS: Linux

Additional context

#7694 avoids the crash only with react_compiler=True or auto_memoize=False, where it renders lifecycle events as an element inside the loop body. Default apps still need a fix. A general fix is to compile each rx.foreach item to its own component, so that every hook of the item runs inside the loop.

Activity

  1. linear-code commented on Nov 10, 2026

    @linear-code
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

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions