nextjs/no-async-client-component 正确性
作用
阻止在 Next.js 应用程序中将 async 函数用于客户端组件。 此规则会检查任何满足以下条件的 async 函数:
- 标记了 "use client" 指令
- 名称以大写字母开头(表示它是一个组件)
- 要么被导出为默认导出,要么被赋值给一个变量
为什么这不好?
在客户端组件中使用 async 函数可能会导致服务端与客户端之间的 hydration 不匹配, 可能会破坏组件渲染生命周期,并且可能会在 React 的并发特性下引发意外行为。
示例
以下是此规则的错误代码示例:
javascript
"use client"
// 带默认导出的 async 组件
export default async function MyComponent() {
return <></>
}
// 带命名导出的 async 组件
async function MyComponent() {
return <></>
}
export default MyComponent
// async 箭头函数组件
const MyComponent = async () => {
return <></>
}
export default MyComponent以下是此规则的正确代码示例:
javascript
"use client"
// 常规同步组件
export default function MyComponent() {
return <></>
}
// 在 effects 中处理 async 操作
export default function MyComponent() {
useEffect(() => {
async function fetchData() {
// 此处为 async 操作
}
fetchData();
}, []);
return <></>
}
// 在事件处理器中处理 async 操作
export default function MyComponent() {
const handleClick = async () => {
// 此处为 async 操作
}
return <button onClick={handleClick}>Click me</button>
}如何使用
To enable this rule using the config file or in the CLI, you can use:
json
{
"plugins": ["nextjs"],
"rules": {
"nextjs/no-async-client-component": "error"
}
}ts
import { defineConfig } from "oxlint";
export default defineConfig({
plugins: ["nextjs"],
rules: {
"nextjs/no-async-client-component": "error",
},
});bash
oxlint --deny nextjs/no-async-client-component --nextjs-plugin版本
此规则在 v0.2.0 中添加。
