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

Next.js 14教程第12章:表单提交未触发Server Action求助

Next.js Server Action 提交表单无响应问题

正在学习Next.js官方教程第12章,完成「3. 从formData提取数据」步骤后,点击表单提交按钮无任何反应,也未出现报错。

相关代码

actions.ts

'use server';
 
export async function createInvoice(formData: FormData) {
  const rawFormData = {
    customerId: formData.get('customerId'),
    amount: formData.get('amount'),
    status: formData.get('status'),
  };
  // Test it out:
  console.log(rawFormData);
}

create-form.tsx

'use client';
...
import { createInvoice } from '@/app/lib/actions';
 
export default function Form({
  customers,
}: {
  customers: CustomerField[];
}) {

  return (
    <form action={createInvoice}>
    ...
        <Button type="submit">Create Invoice</Button>
    ...  
    </form>
  );
}

已做排查操作

  • 移除action改用onSubmit验证,表单提交功能正常
  • 在action中使用简单函数验证,客户端行为正常
  • 清除浏览器缓存排除浏览器问题
  • 新建干净项目复现场景,问题仍存在

问题原因及解决方案

  1. 日志查看位置错误:Server Action 中的console.log输出在服务器终端,而非浏览器控制台。你需要查看启动项目的终端窗口,才能看到rawFormData的打印内容——这是最容易忽略的点,可能你以为没触发,但实际上Server Action已经执行了。

  2. Next.js 版本不兼容:Server Actions 在 Next.js 13.4 及以上版本的 App Router 中才正式稳定可用。执行npm list next查看当前版本,若低于13.4,升级到最新稳定版即可:

npm install next@latest
  1. 旧版本需手动启用配置:如果你的Next.js版本在13.2~13.3之间,需要在next.config.js中手动开启Server Actions:
/** @type {import('next').NextConfig} */
const nextConfig = {
  experimental: {
    serverActions: true,
  },
};

module.exports = nextConfig;
  1. 路径或导入错误:确认createInvoice的导入路径@/app/lib/actions完全匹配实际文件位置,检查是否有拼写错误、目录结构不一致的情况。

内容的提问来源于stack exchange,提问作者Jan Strýček

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 01:08:17