reflex-dev/reflex · error · VarValueError

Cached var {self!s} cannot access arbitrary state `{instruct

Error message

Cached var {self!s} cannot access arbitrary state `{instruction.argval}`, not found in globals.

What it means

When a @rx.var(cached_var) function is scanned, Reflex walks its bytecode to find which state vars it depends on. If the function references a name via LOAD_GLOBAL (e.g. `OtherState.some_var`), Reflex looks that name up in the function module's globals to resolve the state class. If the name is not present there, dependency tracking cannot proceed and VarValueError is raised.

Source

Thrown at packages/reflex-base/src/reflex_base/vars/dep_tracking.py:276

            instruction: The dis instruction to process.

        Raises:
            VarValueError: if the state class cannot be determined from the instruction.
        """
        if isinstance(self.func, CodeType):
            msg = "Dependency detection cannot identify get_state class from a code object."
            raise VarValueError(msg)
        if instruction.opname in ("LOAD_FAST", "LOAD_FAST_BORROW"):
            self._getting_state_class = self.get_tracked_local(
                local_name=instruction.argval,
            )
        elif instruction.opname == "LOAD_GLOBAL":
            # Special case: referencing state class from global scope.
            try:
                self._getting_state_class = self._get_globals()[instruction.argval]
            except (ValueError, KeyError) as ve:
                msg = f"Cached var {self!s} cannot access arbitrary state `{instruction.argval}`, not found in globals."
                raise VarValueError(msg) from ve
        elif instruction.opname == "LOAD_DEREF":
            # Special case: referencing state class from closure.
            try:
                self._getting_state_class = self._get_closure()[instruction.argval]
            except (ValueError, KeyError) as ve:
                msg = f"Cached var {self!s} cannot access arbitrary state `{instruction.argval}`, is it defined yet?"
                raise VarValueError(msg) from ve
        elif instruction.opname in ("LOAD_ATTR", "LOAD_METHOD"):
            self._getting_state_class = getattr(
                self._getting_state_class,
                instruction.argval,
            )
        elif instruction.opname == "GET_AWAITABLE":
            # Now inside the `await` machinery, subsequent instructions
            # operate on the result of the `get_state` call.
            self.scan_status = ScanStatus.GETTING_STATE_POST_AWAIT
            if self._getting_state_class is not None:
                self.top_of_stack = "_"

View on GitHub (pinned to 45b8ed5ab7)

Solutions

  1. Make sure the state class referenced inside the cached var is a real (non-TYPE_CHECKING-only) import at the top of the module where the cached var is defined.
  2. Fix typos in the state class name inside the cached var body.
  3. Break circular imports by moving shared state classes into their own module imported by both parties.
  4. If the global is genuinely unavailable, pass the needed value in as a state var access on `self` instead of a free global reference.

Example fix

# before
from typing import TYPE_CHECKING
if TYPE_CHECKING:
    from .other import OtherState

@rx.var(cached=True)
def combined(self) -> int:
    return self.value + OtherState.value  # OtherState missing at runtime

# after
from .other import OtherState

@rx.var(cached=True)
def combined(self) -> int:
    return self.value + OtherState.value
Defensive patterns

Strategy: validation

Validate before calling

import sys

def state_class_available(name: str, func) -> bool:
    mod = func.__globals__ if hasattr(func, "__globals__") else {}
    return name in mod or name in sys.modules

Try / catch

from reflex.exceptions import VarValueError

try:
    State.computed  # access to trigger dependency tracking at compile
except VarValueError as e:
    if "not found in globals" in str(e):
        # fix imports of the referenced state class
        ...

Prevention

When it happens

Trigger: A cached var function references a state class or other global (e.g. `MyState.foo`) where `MyState` is not actually in that module's globals — typically because of circular imports, the class being defined later, a typo in the state name, or the function being exec'd from a context whose globals don't contain the name.

Common situations: Splitting state classes across modules with circular imports; renaming a state class but not its uses inside cached vars; defining cached vars in a different module from where the state is imported under a `if TYPE_CHECKING` guard; interactive/REPL or dynamically exec'd code where globals are unavailable.

Related errors


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