Next.js部署Vercel时React.FC异步函数类型错误求助
Next.js部署Vercel时的类型错误解决
问题
部署Next.js应用至Vercel时遭遇类型错误,错误信息如下:
Type error: Type ' ({ params }: DashboardPageProps) => Promise' is not assignable to type 'FC
'
Type 'Promise' is not assignable to type 'ReactElement<any, any>'
背景
在./app/(dashboard)/[storeId]/(routes)/page.tsx中定义了页面组件,意图异步获取数据后渲染,但部署过程中触发该类型错误。
代码片段
page.tsx中的相关代码:
// 导入语句 interface DashboardPageProps { params: { storeId: string } } const DashboardPage: React.FC<DashboardPageProps> = async ({ params }) => { const totalRevenue = await getTotalRevenue(params.storeId); const salesCount = await getSalesCount(params.storeId); const stockCount = await getStockCount(params.storeId); const graphRevenue = await getGraphRevenue(params.storeId) return ( // 组件内容 )
环境
- Node.js版本:21.0
解决方法
在Next.js的App Router模式下,页面组件不能直接用React.FC类型声明并定义为异步函数:
- 移除
React.FC类型注解:App Router的页面组件无需React.FC约束,直接定义为异步函数即可,Next.js会自动处理异步页面的类型。 - 调整组件定义方式:将组件改为无
React.FC注解的异步函数,示例如下:
// 导入语句 interface DashboardPageProps { params: { storeId: string } } async function DashboardPage({ params }: DashboardPageProps) { const totalRevenue = await getTotalRevenue(params.storeId); const salesCount = await getSalesCount(params.storeId); const stockCount = await getStockCount(params.storeId); const graphRevenue = await getGraphRevenue(params.storeId) return ( // 组件内容 ) } export default DashboardPage;
原因
React.FC代表同步函数组件,返回值为ReactElement;而异步组件返回的是Promise<ReactElement>,二者类型不兼容。Next.js的App Router原生支持异步页面组件,无需用React.FC做类型约束。
内容的提问来源于stack exchange,提问作者volfcan
相关产品推荐
相关产品推荐

