typescript - Reacthookform dynamic fields , getting TypeError: Cannot assign to read only property '0' of object

admin2025-05-02  1

I am building an complex form data using react hook form , the form data looks like this

Data: {
    form1: string,
    form2: [
        {
            field1: { fields },
            field2: [
                { fields }
            ], // arrays of objects
            field3: { fields }
        }
    ]
}

in the controller name of react hook form i am putting it like this

name=`form2.${currentStateIndex || 0}.field2.fields

where the currentStateIndex is an useState which is trigger from a checkbox to set which index the form field should set data to

but i am getting this error after updating the state , not even after triggering any form.setValue yet

Unhandled Runtime Error
TypeError: Cannot assign to read only property '0' of object '[object Array]'

Call Stack
set
(app-pages-browser)\node_modules\react-hook-form\dist\index.esm.mjs (364:0)
Object.onChange
(app-pages-browser)\node_modules\react-hook-form\dist\index.esm.mjs (1930:0)
Object.eval [as onBlur]
(app-pages-browser)\node_modules\react-hook-form\dist\index.esm.mjs (461:37)

if i change the form name to something concrete like name=`form2.0.field2.fields this error will trigger again but from onChange

Unhandled Runtime Error
TypeError: Cannot assign to read only property '0' of object '[object Array]'

Call Stack
set
(app-pages-browser)\node_modules\react-hook-form\dist\index.esm.mjs (364:0)
Object.onChange
(app-pages-browser)\node_modules\react-hook-form\dist\index.esm.mjs (1930:0)
Object.eval [as onBlur]
(app-pages-browser)\node_modules\react-hook-form\dist\index.esm.mjs (461:37)

i have tried making all of my default values mutable using slice() or clonedeep to no avail

  const form = useForm({
    defaultValues: cloneDeep(generateDefaultValues({})),
    resolver: zodResolver(Schema),
    mode: 'onChange'
  });

please let me know if you have ran into the same problem , thanks

转载请注明原文地址:http://www.anycun.com/QandA/1746135344a92060.html