{"record":{"id":"40f05f0a25bdf5ec","repo":"cocoindex-io/cocoindex","slug":"coco-use-state-cannot-be-called-inside-a-with-c","errorCode":null,"errorMessage":"coco.use_state() cannot be called inside a `with coco.component_subpath()` block","messagePattern":"coco\\.use_state\\(\\) cannot be called inside a `with coco\\.component_subpath\\(\\)` block","errorType":"exception","errorClass":"RuntimeError","httpStatus":null,"severity":"error","filePath":"python/cocoindex/_internal/api.py","lineNumber":862,"sourceCode":"\n    Example::\n\n        # Plain (value typed as Any)\n        counter = coco.use_state(\"counter\", 0)\n\n        # Typed — handle.value is Cursor, with full type inference\n        @dataclass\n        class Cursor:\n            pos: int\n            tag: str\n\n        cur = coco.use_state(\"cursor\", type_hint=Cursor, initial_value=Cursor(0, \"init\"))\n        cur.value.pos += 1\n        cur.value = Cursor(cur.value.pos, \"next\")\n    \"\"\"\n    ctx = get_context_from_ctx()\n    if ctx._core_path != ctx._core_processor_ctx.stable_path:\n        raise RuntimeError(\n            \"coco.use_state() cannot be called inside a `with coco.component_subpath()` block\"\n        )\n\n    if ctx._in_memo_fn:\n        raise RuntimeError(\n            \"coco.use_state() cannot be called inside a memoized function\"\n        )\n    try:\n        # initial_value passed unserialized; engine core drops it if a value is\n        # already stored on the previous run for this key.\n        stored = ctx._core_processor_ctx.use_state(key, initial_value)\n    except ValueError as e:\n        # Rust client errors surface as ValueError; normalize to RuntimeError so\n        # all use_state usage errors have a consistent type for callers.\n        raise RuntimeError(str(e)) from None\n    if type_hint is not None:\n        deserializer = get_deserialize_fn(\n            type_hint,  # type: ignore[arg-type]  # type objects are hashable at runtime","sourceCodeStart":844,"sourceCodeEnd":880,"githubUrl":"https://github.com/cocoindex-io/cocoindex/blob/e84aa99b3292c5270a4b313b2a7137ad9ce8ab3b/python/cocoindex/_internal/api.py#L844-L880","documentation":"use_state() attaches state to the current processing component's stable path. Inside a `with coco.component_subpath()` block the ambient path is temporarily re-routed, so state would be keyed to the wrong path; the API detects this mismatch and refuses.","triggerScenarios":"Calling coco.use_state(...) on the current component context while inside a `with coco.component_subpath(...):` block, where ctx._core_path differs from the processor's stable_path.","commonSituations":"Wrapping a section of a component body in component_subpath() to namespace nested mounts, and accidentally calling use_state() inside that block; reworking code that moved use_state inside the with-block during refactoring.","solutions":["Move the coco.use_state() call outside the `with coco.component_subpath()` block","If state is needed for the nested subpath, mount it as its own component (use_mount/mount) and call use_state within that component"],"exampleFix":"// before\nwith coco.component_subpath(\"phase\"):\n    cur = coco.use_state(\"cursor\", initial_value=Cursor(0, \"init\"))\n// after\ncur = coco.use_state(\"cursor\", initial_value=Cursor(0, \"init\"))\nwith coco.component_subpath(\"phase\"):\n    ...","handlingStrategy":"validation","validationCode":"# call use_state before entering any component_subpath block\nstate = coco.use_state(\"cursor\", initial_value=Cursor(0, \"init\"))\nwith coco.component_subpath(\"phase\"):\n    ...  # no use_state here","typeGuard":null,"tryCatchPattern":"try:\n    cur = coco.use_state(\"cursor\", initial_value=Cursor(0, \"init\"))\nexcept RuntimeError as e:\n    if \"component_subpath()\" in str(e):\n        raise  # restructure: move use_state outside the with-block","preventionTips":["Treat use_state as component-body-only code, never inside subpath blocks","Keep state initialization at the top of the component body before any with-blocks"],"tags":["python","state","api-misuse"],"backgroundTag":"invalid-state-transition","analyzedSha":"e84aa99b3292c5270a4b313b2a7137ad9ce8ab3b","analyzedAt":"2026-09-08T15:59:19.997Z","contentChangedAt":"2026-09-08T15:59:19.997Z","schemaVersion":2},"datasetVersion":"2026-09-14T05:17:10.506Z"}