reflex-dev/reflex · error · RuntimeError

Context is already attached, cannot enter context manager.

Error message

Context is already attached, cannot enter context manager.

What it means

Raised when entering a Context object that is already active in the current execution context. Reflex contexts use a contextvar token stored per-instance (_attached_context_token) to detect double entry; entering twice would corrupt restore semantics, so it raises RuntimeError immediately.

Source

Thrown at packages/reflex-base/src/reflex_base/context/base.py:64

    @classmethod
    def reset(cls, token: Token[Self]) -> None:
        """Reset the context variable to a previous state.

        Args:
            token: The token to reset the context variable to.
        """
        cls._context_var.reset(token)

    def __enter__(self) -> Self:
        """Enter the context.

        Returns:
            This context instance.
        """
        if self._attached_context_token.get(self) is not None:
            msg = "Context is already attached, cannot enter context manager."
            raise RuntimeError(msg)
        self._attached_context_token[self] = self._context_var.set(self)
        return self

    def __exit__(self, *exc_info):
        """Exit the context."""
        if (token := self._attached_context_token.pop(self, None)) is not None:
            self._context_var.reset(token)

    def ensure_context_attached(self):
        """Ensure that the context is attached to the current context variable.

        Raises:
            RuntimeError: If the context is not attached.
        """
        if self._attached_context_token.get(self) is None:
            msg = f"{type(self).__name__} must be entered before calling this method."
            raise RuntimeError(msg)

View on GitHub (pinned to 45b8ed5ab7)

Solutions

  1. Ensure each `with ctx:` / `async with ctx:` block is exited before re-entering the same instance
  2. Create a fresh Context instance per scope instead of reusing a shared one
  3. Audit helper functions that enter the context and make sure callers don't also enter it

Example fix

# before
ctx = rx.context(...)  # shared instance
with ctx:
    ...
with ctx:  # RuntimeError: already attached
    ...
# after
with make_context() as ctx1:
    ...
with make_context() as ctx2:
    ...
Defensive patterns

Strategy: type-guard

Validate before calling

if ctx._attached_context_token.get(ctx) is not None:
    raise RuntimeError("context already entered — reuse blocked")

Type guard

def is_context_attached(ctx) -> bool:
    return ctx._attached_context_token.get(ctx) is not None

Try / catch

null

Prevention

When it happens

Trigger: Calling ctx.__enter__() (e.g. `with ctx:`) or `async with ctx:` on a Context instance that is already inside an active with-block, or re-entering the same context object in a nested block within the same task.

Common situations: Nesting `with ctx:` blocks accidentally, sharing a module-level Context instance across requests/tasks, or wrapping already-entered context in a helper that also enters it.

Related errors


AI-assisted analysis of reflex-dev/reflex@45b8ed5ab7 (2026-08-28). Data as JSON: /api/errors/dda016b9f0dee498. Report an issue: GitHub.