fix(form-core): reset stale validation counter when shifting array meta #2247
main fromrefs/pull/2247/head·opened 🎯 Changes#
Fixes #2234. When an array item is removed (or inserted/moved) while an async validator is in flight, shiftMeta copied the source field's transient _pendingValidationsCount/isValidating down to the shifted index. The pending promise is owned by the original field instance and settles its counter against the original index, so the shifted index's counter is orphaned and never decremented — leaving form.state.isFieldsValidating stuck true and blocking submission.
shiftMetanow resets the transient validation state (isValidating,_pendingValidationsCount) when shifting meta between indices. Array mutations already re-trigger validation on the shifted fields, so this is safe.endValidationbails out if the field's instance is no longer registered, so a validation that resolves after its field was removed no longer resurrects deleted meta (previously threw aTypeError).
✅ Checklist#
- I have followed the steps in the Contributing guide.
- I have tested this code locally.
🚀 Release Impact#
- This change affects published code, and I have generated a changeset.
Summary by CodeRabbit#
- Bug Fixes
- Fixed an issue where async validation state could remain stuck after removing an item from an array field during in-flight validation.
- Ensured transient async-validation indicators are properly reset or preserved when array field metadata shifts due to move, swap, or shift operations.
- Tests
- Added coverage for array remove/move/swap scenarios with in-flight async validation, verifying field-level and form-level validating status behavior.
- 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
packages/form-core/src/metaHelper.ts (1)
100-116: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick winReset async-validation state in
handleArrayMove/handleArraySwap. ReapplyingfromMetaand swapping meta verbatim carriesisValidatingand_pendingValidationsCountto the new index, so an in-flight validation can stay stuck on the wrong field. MirrorshiftMeta’s reset here and add a move/swap regression test.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/form-core/src/metaHelper.ts` around lines 100 - 116, Reset async-validation state when restoring metadata in handleArrayMove and handleArraySwap, matching shiftMeta’s reset behavior instead of copying isValidating and _pendingValidationsCount unchanged. Update the metadata transfer logic around fromMeta and swapped metadata, then add regression coverage verifying moved and swapped fields do not retain in-flight validation state.🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. Outside diff comments: In `@packages/form-core/src/metaHelper.ts`: - Around line 100-116: Reset async-validation state when restoring metadata in handleArrayMove and handleArraySwap, matching shiftMeta’s reset behavior instead of copying isValidating and _pendingValidationsCount unchanged. Update the metadata transfer logic around fromMeta and swapped metadata, then add regression coverage verifying moved and swapped fields do not retain in-flight validation state.
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID:
48e8bfdf-c589-40d8-979e-008a9b920059📥 Commits
Reviewing files that changed from the base of the PR and between 5d1128141a705ebb24ade1275b3117bb4c8b1bdc and 351d7521418373ad78dc6d9917f0b8d73e063db8.
📒 Files selected for processing (4)
.changeset/fix-array-removevalue-isvalidating-stuck.mdpackages/form-core/src/FieldApi.tspackages/form-core/src/metaHelper.tspackages/form-core/tests/FieldApi.spec.ts
Addressed the CodeRabbit follow-up in 8488fc3. Move and swap now use the same transient async-validation reset as shifted array meta, so
isValidating/_pendingValidationsCountare not copied to a different index. Added regression coverage for bothmoveValueandswapValues.Local checks:
PATH=/Users/even/.nvm/versions/node/v24.18.0/bin:$PATH pnpm --dir packages/form-core test:lib tests/FieldApi.spec.tsPATH=/Users/even/.nvm/versions/node/v24.18.0/bin:$PATH pnpm --dir packages/form-core test:types:ts59
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. Inline comments: In `@packages/form-core/src/metaHelper.ts`: - Around line 113-116: Preserve validation metadata for no-op operations by returning early when fromIndex === toIndex in moveValue at packages/form-core/src/metaHelper.ts:113-116, and when index === secondIndex in swapValues at packages/form-core/src/metaHelper.ts:159-162, before resetting field metadata. Add regression coverage for same-index moveValue and swapValues calls with dontValidate enabled to verify pending validation remains intact.🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID:
406bd3eb-5e14-4388-a433-7a8336813edd📥 Commits
Reviewing files that changed from the base of the PR and between 351d7521418373ad78dc6d9917f0b8d73e063db8 and 8488fc302ec7a012a8944e4f67be2b3f6c4e5d84.
📒 Files selected for processing (2)
packages/form-core/src/metaHelper.tspackages/form-core/tests/FieldApi.spec.ts
@@ -110,4 +110,7 @@110110111111 const fromMeta = fromFields.get(fromKey)112112 if (fromMeta) {113- formApi.setFieldMeta(fieldKey as DeepKeys<TFormData>, fromMeta)113+ formApi.setFieldMeta(114+ fieldKey as DeepKeys<TFormData>,115+ resetTransientValidationMeta(fromMeta),116+ )🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Preserve validation state for no-op moves and swaps.
moveValue(i, i, { dontValidate: true })andswapValues(i, i, { dontValidate: true })operate on the same metadata key, but these resets mark an in-flight validation as complete despite no field instance moving.packages/form-core/src/metaHelper.ts#L113-L116: return early whenfromIndex === toIndex.packages/form-core/src/metaHelper.ts#L159-L162: return early whenindex === secondIndex.- Add same-index regression coverage to ensure pending validation state remains intact.
Proposed fix
function handleArrayMove(field, fromIndex, toIndex) { bumpArrayVersion(field) + if (fromIndex === toIndex) return // ... } function handleArraySwap(field, index, secondIndex) { bumpArrayVersion(field) + if (index === secondIndex) return // ... }📝 Committable suggestion
‼️ IMPORTANT Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
function handleArrayMove(field, fromIndex, toIndex) { bumpArrayVersion(field) if (fromIndex === toIndex) return // ... } function handleArraySwap(field, index, secondIndex) { bumpArrayVersion(field) if (index === secondIndex) return // ... }📍 Affects 1 file
packages/form-core/src/metaHelper.ts#L113-L116(this comment)packages/form-core/src/metaHelper.ts#L159-L162
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/form-core/src/metaHelper.ts` around lines 113 - 116, Preserve validation metadata for no-op operations by returning early when fromIndex === toIndex in moveValue at packages/form-core/src/metaHelper.ts:113-116, and when index === secondIndex in swapValues at packages/form-core/src/metaHelper.ts:159-162, before resetting field metadata. Add regression coverage for same-index moveValue and swapValues calls with dontValidate enabled to verify pending validation remains intact.✅ Addressed in commit 860ab18
Addressed the same-index move/swap follow-up in
860ab18.What changed:
moveValue(i, i, { dontValidate: true })now returns after bumping the array version, before meta shifting/resetting.swapValues(i, i, { dontValidate: true })does the same.- Added regression coverage to verify
isValidatingand_pendingValidationsCountremain intact for both no-op operations.
Local check:
pnpm --filter @tanstack/form-core exec vitest run tests/FieldApi.spec.tsResult: 1 file / 110 tests passed, no type errors.
Checked how
this.getInfo().instance !== thisis used elsewhere inFieldApi.tsbefore judging this guard, and it's not a new idea being introduced here, the async validator resolution path around line 1554 already bails out of writingsetMetawith that exact same check when a field's identity has been superseded. SoendValidation()picking up the same guard is consistent with how the file already treats "this instance no longer owns this name" elsewhere, rather than a one-off patch.What makes this actually close the bug rather than just move it is that
endValidation()runs unconditionally afterPromise.all(validatesPromises)invalidateAsync, regardless of that existing instance check further up (which only guards the error-writingsetMeta, not the counter decrement). So before this fix, even in the path that correctly skipped writing a stale error, the pending-validation counter on whatever now occupies that field name would still get decremented by an instance that no longer owns it, which is exactly howisFieldsValidatingcould end up permanently wrong afterremoveValueshifts indices.The
resetTransientValidationMetaaddition inmetaHelper.tsis the other half of the same problem: when array mutation copies old meta onto a new key, carrying overisValidating/_pendingValidationsCountwould leave a counter at the new key that nothing will ever decrement, since the instance that started that validation is bailing out via the guard above instead of settling it. Resetting it at copy time and letting the shift naturally re-trigger validation on the moved field is the right call.The
fromIndex === toIndex/index === secondIndexearly returns are a nice touch beyond the core fix, and the test for the same-index case (should preserve transient async validation state when moving array field meta to the same index) is what actually proves the reset only fires on a real move and not on a no-op call, which is easy to get backwards.The main regression test reconstructs the real scenario end to end, an async validator on a listened-to field, in flight, then removing a different array index while it's pending, then resolving it and checking the counter settles at zero rather than asserting some internal method got called. That's the right level to test this at since the bug only shows up through that exact interleaving.
xianjianlf2(GitHub profile, opens in a new tab) linked this to fix #2234
Sign in to join this conversation.
No actionable comments were generated in the recent review. 🎉
ℹ️ Recent review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID:
a6b3d838-b1f1-4f66-b29f-519d159a421f📥 Commits
Reviewing files that changed from the base of the PR and between 8488fc302ec7a012a8944e4f67be2b3f6c4e5d84 and 860ab1866a8932b3cbf045be4e0af84c0776be95.
📒 Files selected for processing (2)
packages/form-core/src/metaHelper.tspackages/form-core/tests/FieldApi.spec.ts🚧 Files skipped from review as they are similar to previous changes (1)
📝 Walkthrough
Walkthrough#
This change prevents stale async-validation state after array values are removed or reordered by guarding inactive field validation completion and resetting transient metadata during shifts. Tests cover removal, move, and swap scenarios, with a patch Changesets entry.
Changes#
Array async-validation cleanup
packages/form-core/src/FieldApi.ts,packages/form-core/src/metaHelper.tsisValidatingand_pendingValidationsCount.packages/form-core/tests/FieldApi.spec.ts,.changeset/fix-array-removevalue-isvalidating-stuck.mdEstimated code review effort: 2 (Simple) | ~10 minutes
Possibly related PRs
isValidatingresolution inFieldApi.ts.Suggested reviewers:
crutchcorn,crutchcorn🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
✨ Finishing Touches
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
❤️ Share