Skip to content

Bug: setFieldValue crashes with "Cannot read properties of undefined (reading 'onServer')" in v1.27.5 #1947

@furaihan

Description

@furaihan

Describe the bug

Calling form.setFieldValue() on a field that has not been mounted/registered yet can cause a runtime crash in TanStack Form v1.27.5 with the following error:
Cannot read properties of undefined (reading 'onServer')
This appears to be a regression introduced in v1.27.5.
The same behavior works without crashing in v1.27.4.

Your minimal, reproducible example

https://codesandbox.io/p/sandbox/sf3wq2

Steps to reproduce

import { useEffect, useState } from 'react';
import { useForm } from '@tanstack/react-form';

type DetailItem = {
  id: number;
  qty: number;
};

export function BugRepro() {
  const [mountDetailsFields, setMountDetailsFields] = useState(false);

  const form = useForm({
    defaultValues: { details: [] as DetailItem[] },
    validators: {
      onSubmit: ({ value }) => {
        if (!value.details.length) {
          return {
            details: 'Details is required',
          };
        }
        return {};
      },
    },
  });

  const handleAddItem = () => {
    const current = form.state.values.details ?? [];
    // Update field before it is mounted
    form.setFieldValue('details', [...current, { id: 1, qty: 10 }]);
    setMountDetailsFields(true);
  };

  useEffect(() => {
    if (!mountDetailsFields) return;

    // Trigger sync validation after field mounts
    const id = setTimeout(() => {
      (form as any).validateSync('change');
    }, 0);

    return () => clearTimeout(id);
  }, [form, mountDetailsFields]);

  return (
    <div>
      <button onClick={handleAddItem}>Add Item</button>

      {mountDetailsFields ? (
        <>
          <form.Field name="details">{() => null}</form.Field>
          <form.Field name="details[0].id">{() => null}</form.Field>
          <form.Field name="details[0].qty">{() => null}</form.Field>
        </>
      ) : null}
    </div>
  );
}
  1. Install @tanstack/[email protected]
  2. Render the component above
  3. Click “Add Item”
  4. Application crashes with:
    Cannot read properties of undefined (reading 'onServer')

Expected behavior

Calling setFieldValue should not crash the application, even if the field is updated before being mounted.
This behavior worked as expected in v1.27.4.

How often does this bug happen?

Every time

Screenshots or Videos

No response

Platform

Windows

TanStack Form adapter

react-form

TanStack Form version

1.27.5

TypeScript version

5.9.3

Additional context

No response

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