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

新版TypeScript下Async Server Component抛出错误求助

解决Next.js中Async组件TS报错问题

核心原因

在Next.js App Router中,只有Server Component支持直接使用async/await获取数据,客户端组件不能定义为async函数。即便你的TS和@types/react版本满足React官方的async组件要求,Next.js的组件模型仍有这个限制。

解决方案

方案1:将Main组件作为Server Component使用

确保你的Main组件没有使用客户端专属API(如useState、useEffect、window对象等),也没有添加'use client'指令。同时检查项目配置:

  • 确认tsconfig.json中的compilerOptions.jsx设置为"react-jsx"或"react-jsxdev"
  • 确保next.config.js中没有禁用Server Component相关配置

你的现有main.tsx代码本身无客户端依赖,属于Server Component范畴,保持原样即可。

方案2:如果Main需要作为客户端组件(含交互逻辑)

若后续需要给Main组件添加客户端交互(比如按钮点击状态),则不能用async组件,改用useEffect配合状态管理数据:

import { useEffect, useState } from 'react';
import { getAllProjects, Project } from "./utils/db/projects"
import { Button }  from '@/components'

export default function Main() {
    const [projects, setProjects] = useState<Project[]>([]);
    const [loading, setLoading] = useState(true);

    useEffect(() => {
        const fetchProjects = async () => {
            const data = await getAllProjects();
            setProjects(data);
            setLoading(false);
        };
        fetchProjects();
    }, []);

    if (loading) {
        return <div>Loading...</div>;
    }

    return (
        <>
            <h1 className="text-4xl font-bold">
                {projects.length < 1 ? " Looks you don't have any projects yet." : 
                projects.length == 1 ? "Here is your project!" : 
                "Here are your projects!" } 
            </h1>
            <Button>Create new project</Button>
        </>
    )
}

方案3:检查Next.js版本匹配

Next.js从13.4版本开始稳定支持Server Component的async/await,确保你的next版本≥13.4:

# 查看当前Next.js版本
npm list next
# 版本过低则升级到最新稳定版
npm install next@latest

额外排查点

  • 确保@types/react-dom版本与@types/react一致,避免类型定义冲突
  • 清除TS缓存:删除.next文件夹和node_modules/.cache,重新编译项目

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 19:10:12