{"record":{"id":"c99b9c1492306979","repo":"reflex-dev/reflex","slug":"cached-var-self-s-cannot-access-arbitrary-state-c99b9c","errorCode":null,"errorMessage":"Cached var {self!s} cannot access arbitrary state `{instruction.argval}`, is it defined yet?","messagePattern":"Cached var (.+?) cannot access arbitrary state `(.+?)`, is it defined yet\\?","errorType":"exception","errorClass":"VarValueError","httpStatus":null,"severity":"error","filePath":"packages/reflex-base/src/reflex_base/vars/dep_tracking.py","lineNumber":283,"sourceCode":"            raise VarValueError(msg)\n        if instruction.opname in (\"LOAD_FAST\", \"LOAD_FAST_BORROW\"):\n            self._getting_state_class = self.get_tracked_local(\n                local_name=instruction.argval,\n            )\n        elif instruction.opname == \"LOAD_GLOBAL\":\n            # Special case: referencing state class from global scope.\n            try:\n                self._getting_state_class = self._get_globals()[instruction.argval]\n            except (ValueError, KeyError) as ve:\n                msg = f\"Cached var {self!s} cannot access arbitrary state `{instruction.argval}`, not found in globals.\"\n                raise VarValueError(msg) from ve\n        elif instruction.opname == \"LOAD_DEREF\":\n            # Special case: referencing state class from closure.\n            try:\n                self._getting_state_class = self._get_closure()[instruction.argval]\n            except (ValueError, KeyError) as ve:\n                msg = f\"Cached var {self!s} cannot access arbitrary state `{instruction.argval}`, is it defined yet?\"\n                raise VarValueError(msg) from ve\n        elif instruction.opname in (\"LOAD_ATTR\", \"LOAD_METHOD\"):\n            self._getting_state_class = getattr(\n                self._getting_state_class,\n                instruction.argval,\n            )\n        elif instruction.opname == \"GET_AWAITABLE\":\n            # Now inside the `await` machinery, subsequent instructions\n            # operate on the result of the `get_state` call.\n            self.scan_status = ScanStatus.GETTING_STATE_POST_AWAIT\n            if self._getting_state_class is not None:\n                self.top_of_stack = \"_\"\n                self.tracked_locals[self.top_of_stack] = self._getting_state_class\n                self._getting_state_class = None\n\n    def handle_getting_state_post_await(self, instruction: dis.Instruction) -> None:\n        \"\"\"Handle bytecode analysis after `get_state` was called in the function.\n\n        This function is called _after_ awaiting self.get_state to capture the","sourceCodeStart":265,"sourceCodeEnd":301,"githubUrl":"https://github.com/reflex-dev/reflex/blob/45b8ed5ab735f8a56bbb09a42384f030eb0208e7/packages/reflex-base/src/reflex_base/vars/dep_tracking.py#L265-L301","documentation":"During dependency tracking of a cached var, Reflex resolves names loaded from closures (LOAD_DEREF). If the closure cell for the referenced name is missing or not yet populated (KeyError/ValueError), Reflex cannot tell which state class is being accessed and raises VarValueError.","triggerScenarios":"A cached var function closes over a name (e.g. a state class defined later in the same module, or a closure variable that is unbound at scan time) and references it like `ClosedState.value`. The name is not yet in the function's closure when Reflex inspects the bytecode.","commonSituations":"Defining a state class after the cached var that references it inside the same module; late-binding closures; partial functions or decorators that capture names defined conditionally; module reload/dynamic definition ordering issues.","solutions":["Move the definition of the closed-over name (state class) above the cached var that uses it.","Convert the closure reference into a direct module-level import so it resolves via LOAD_GLOBAL from globals.","If the name is defined conditionally, restructure so it is always defined before the cached var is declared."],"exampleFix":"# before\n@rx.var(cached=True)\ndef total(self) -> int:\n    return self.v + LaterState.v  # LaterState defined below\n\nclass LaterState(rx.State):\n    v: int = 0\n\n# after\nclass LaterState(rx.State):\n    v: int = 0\n\n@rx.var(cached=True)\ndef total(self) -> int:\n    return self.v + LaterState.v","handlingStrategy":"validation","validationCode":"def closure_cell_defined(func, name: str) -> bool:\n    if func.__closure__ is None:\n        return False\n    names = func.__code__.co_freevars\n    return name in names and dict(zip(names, func.__closure__)).get(names.index(name)) is not None","typeGuard":null,"tryCatchPattern":null,"preventionTips":["Define state classes before cached vars that reference them.","Prefer module-level imports over closure captures in cached vars.","Keep module definition order stable when refactoring."],"tags":["reflex","cached-var","closure","dependency-tracking"],"backgroundTag":"cached-var-unresolved-global","analyzedSha":"45b8ed5ab735f8a56bbb09a42384f030eb0208e7","analyzedAt":"2026-08-28T19:25:27.644Z","schemaVersion":2},"datasetVersion":"2026-08-28T21:17:43.275Z"}