Skip to content

State var default of dataclasses.field(...) fails with TypeError: cannot pickle 'mappingproxy' object #7017

Description

@FarhanAliRaza

Description

A state var can take its default from dataclasses.field(default_factory=...). Reflex accepts the class definition. The app then fails when it builds the initial state. The error is TypeError: cannot pickle 'mappingproxy' object.

The cause is the dataclasses.Field object itself. Reflex keeps that object as the default value. It then deep-copies it. Field.metadata is a mappingproxy, and copy.deepcopy cannot copy it.

The supported form is rx.field(default_factory=...). Both forms look correct to a user. The error message names neither the field nor the correct form.

Steps to reproduce

import dataclasses

import reflex as rx


@dataclasses.dataclass
class Item:
    tag: str = "a"


class State(rx.State):
    # `rx.field(default_factory=Item)` works. This line does not.
    item: Item = dataclasses.field(default_factory=Item)


def index() -> rx.Component:
    return rx.text(State.item.tag)


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

Run reflex run. The frontend compile step fails.

Actual result

File "reflex/compiler/utils.py", line 221, in compile_state
    initial_state = state(_reflex_internal_init=True).dict(initial=True)
File "reflex/state.py", line 484, in __init__
    self.substates[substate.get_name()] = substate(
File "packages/reflex-base/src/reflex_base/vars/base.py", line 3888, in __init__
    default_value = value.default_value()
File "packages/reflex-base/src/reflex_base/vars/base.py", line 3569, in default_value
    return self.default_factory()
File "/usr/lib/python3.14/copy.py", line 240, in _reconstruct
    state = deepcopy(state, memo)
...
TypeError: cannot pickle 'mappingproxy' object

Expected result

Reflex rejects the value when it builds the state class. The message names the field. The message says to use rx.field(...) instead.

Alternatively, Reflex reads the default_factory from the dataclasses.Field object and uses it.

Environment

  • main at dd96aea55 (2026-08-28)
  • Python 3.14.4
  • Linux

Notes

I found this while I built a test app for #7014. The fault is not related to that PR. It reproduces on a clean main.

Activity

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