Error: Functions cannot be passed directly to Client Components unless you explicitly expose it by marking it with "use server"

Raf*_*ski 34 reactjs next.js

Got this error message in Next.js but have no idea what to do with this. Next.js version 13.0.5.

I was passing a prop to a client component in Next.js. Prop is the list of objects, and one of the values is a function. But the question is, what this error message means?

Error: Functions cannot be passed directly to Client Components unless you explicitly expose it by marking it with "use server"

How can I expose a function by marking it with "use server"?

matchesColumns.push({ field: 'pk', headerName: "", flex: 0.3, renderCell: (params, event) => (<Link href={`/matches/${encodeURIComponent(params.row.pk)}`}>Details</Link>) });
(...)
{<Tabela2 rows={matchesRows} columns={matchesColumns}/>}
Run Code Online (Sandbox Code Playgroud)

Joo*_*nas 24

这是 Next.js 即将推出的一项新功能,称为服务器操作。

您可以使用服务器操作将异步函数从服务器传递到客户端组件,同时仍然可以从客户端调用它们。

这是一个例子:

// page.tsx

"use server";

import { ClientComponent } from './ClientComponent.tsx';

async function deleteItem(itemId: string) {
  "use server"; // mark function as a server action (fixes the error)

  // TODO add item deletion logic
  return null;
}

export function Page() {
  return <ClientComponent deleteItem={deleteItem} />
}
Run Code Online (Sandbox Code Playgroud)
// ClientComponent.tsx

export function ClientComponent({ deleteItem }) {
  return (
    <button onClick={async () => {
      await deleteItem("foobar");
      alert("item has been deleted");
    }}>
      delete item
    </button>
  );
}
Run Code Online (Sandbox Code Playgroud)

  • 谢谢!在 NextJS 版本 13.4.19 上,此代码给出“服务器操作必须是异步函数”,并且使 Page() 异步再次给出问题中的错误。要修复它,请删除第一个“使用服务器”。 (2认同)

小智 7

如果您在error.(jsx|tsx)文件中遇到此错误,请注意该error.(jsx|tsx)文件必须标记为客户端组件。

文档参考

  • 通过额外的支持信息可以改进您的答案。请[编辑]添加更多详细信息,例如引文或文档,以便其他人可以确认您的答案是正确的。您可以[在帮助中心](/help/how-to-answer)找到有关如何写出好的答案的更多信息。 (3认同)