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

Next.js 14函数传递错误修复请求:已加"use server"仍报错

问题修复:Next.js 14 函数传递给客户端组件错误

错误信息

Error: Functions cannot be passed directly to Client Components unless you explicitly expose it by marking it with "use server".
{id: 1, label: ..., icon: function, images: ...}

问题根源

服务端组件Collections中,categories数组的每一项包含了icon函数属性。当你把整个category对象传递给客户端组件ProductCard时,这个函数被直接传给了客户端组件——Next.js禁止未通过"use server"标记的函数在服务端与客户端组件之间传递,即便服务端组件本身加了"use server"也无效,问题核心是传递的对象里包含未被允许的函数。

解决方案

在服务端组件向客户端组件传递数据前,过滤掉category对象里的函数属性,只保留客户端组件实际需要的纯数据字段(比如id、name、images,这些是ProductCard里用到的)。

修改后的服务端组件代码

"use server";
import Container from "../components/Container";
import CollectionCard from "../components/products/CollectionCard";
import getProducts, { IProductParams } from "@/actions/getProducts";
import NullData from "../components/NullData";
import Heading from "../components/Headings";
import { categories } from "@/utils/categories";

export default async function Collections() {
  return (
    <Container>
      <div className="mt-10">
        <Heading title="Collections" center />
      </div>

      <div
        className="mt-10 grid 
        grid-cols-1
        sm:grid-cols-1 
        lg:grid-cols-4
        xl:grid-col-4
        2xl:grid-col-4 
        gap-8"
      >
        {categories.map((category: any) => {
          // 过滤掉函数属性,只保留纯数据字段
          const { icon, ...categoryData } = category;
          return <CollectionCard key={category.id} data={categoryData} />;
        })}
      </div>
    </Container>
  );
}

按需选取字段的写法(更明确)

如果你想精准控制传递的字段,可直接解构需要的属性:

categories.map((category: any) => {
  const { id, name, images } = category;
  return <CollectionCard key={id} data={{ id, name, images }} />;
})

说明

客户端组件ProductCard仅用到data.id、data.name、data.images,只传递这些纯数据字段,避免传递icon这类函数属性,即可解决该错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 09:43:34