You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Next.js 14 TypeScript Server Action表单处理:FormData.get报错解决

Next.js 14 + TypeScript Server Action表单提交错误修复

错误原因

Error: e._formData.get is not a function 是因为传入Server Action的参数并非标准FormData实例,而是Next.js内部封装的对象,直接调用.get()方法会触发错误。

正确处理方案

方案1:重新封装为标准FormData

修改handleAuth函数,将传入参数转换为标准FormData:

export default async function PageDashboard() {
  async function handleAuth(formData: FormData) {
    "use server";
    const standardFormData = new FormData(formData as Iterable<[string, FormDataEntryValue]>);
    
    const data = {
      email: standardFormData.get("email"),
      password: standardFormData.get("password"),
    };

    console.log(data);
  }

  return (
    <form className="space-y-6" action={handleAuth}>
      <input name="email" placeholder="Email" className="border" />
      <input name="password" placeholder="Password" className="border" />
      <button name="submit" type="submit" className="border">
        Submit
      </button>
    </form>
  );
}

方案2:用Object.fromEntries快速解构表单数据

更简洁的方式是将表单数据转为普通对象:

export default async function PageDashboard() {
  async function handleAuth(formData: FormData) {
    "use server";
    const data = Object.fromEntries(formData) as {
      email: string;
      password: string;
    };

    console.log(data);
  }

  return (
    <form className="space-y-6" action={handleAuth}>
      <input name="email" placeholder="Email" className="border" />
      <input name="password" placeholder="Password" className="border" />
      <button name="submit" type="submit" className="border">
        Submit
      </button>
    </form>
  );
}

方案3:确认Server Actions配置

如果仍有问题,检查next.config.js是否启用Server Actions(Next.js 14默认启用,若手动关闭需重新开启):

/** @type {import('next').NextConfig} */
const nextConfig = {
  experimental: {
    serverActions: true,
  },
};

module.exports = nextConfig;

关键注意点

  • 页面组件需为服务器组件(async函数定义的页面默认是服务器组件),Server Action必须在服务器组件或服务器端导出的函数中定义。
  • 表单直接绑定Server Action到action属性即可,无需额外监听onSubmit事件。

内容的提问来源于stack exchange,提问作者imprs

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 23:12:39