谷粒的泥坑

🌿谷粒的生活笔记 —— 在数字世界的泥坑中,播种代码、文字的种子,静待每一份热爱自然生长

nextjs项目在 npm run build的时候报错了,报错信息如下 Types of property 'searchParams' are incompatible

nextjs项目在 npm run build的时候报错了,报错信息如下 Type error: Type ‘{ searchParams: { paymentIntentId?: string | undefined; orderId?: string | undefined; }; }’ does not satisfy the constraint ‘PageProps’. Types of property ‘searchParams’ are incompatible. Type ‘{ paymentIntentId?: string | undefined; orderId?: string | undefined; }’ is missing the following properties from type ‘Promise‘: then, catch, finally, [Symbol.toStringTag]

nextjs项目在 npm run build的时候报错了,报错信息如下 Type error: Type ‘{ searchParams: { paymentIntentId?: string | undefined; orderId?: string | undefined; }; }’ does not satisfy the constraint ‘PageProps’. Types of property ‘searchParams’ are incompatible. Type ‘{ paymentIntentId?: string | undefined; orderId?: string | undefined; }’ is missing the following properties from type ‘Promise‘: then, catch, finally, [Symbol.toStringTag]

这个错误是因为 Next.js 14+ 对页面的 searchParams 类型定义发生了变化,searchParams现在应该是一个 Promise 类型。你需要修改你的页面组件来适应这个变化。

以下是修改后的 thank-you/page.tsx 代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import { Text, Title, Card, SimpleGrid, Box, Group } from "@mantine/core";
import { ReactElement } from "react";
import { FaRegCreditCard } from "react-icons/fa";

export default async function ThankYouPage({
searchParams,
}: {
searchParams: Promise<{
paymentIntentId?: string;
orderId?: string;
}>;
}): Promise<ReactElement> {
const params = await searchParams;
const { paymentIntentId, orderId } = params || {};

return (
<Box style={{ background: "linear-gradient(to bottom, #fff, #f9fafb)" }} className="py-12">
<Title order={1} ta="center" mb="lg">
Thank You for Your Purchase!
</Title>

<SimpleGrid cols={1} spacing="lg" mt="lg" className="max-w-3xl mx-auto">
{paymentIntentId && (
<Card shadow="sm" padding="lg" radius="md" withBorder>
<Group>
<FaRegCreditCard size={24} />
<div>
<Text fw={700}>Payment Intent ID:</Text>
<Text c="dimmed">{paymentIntentId}</Text>
</div>
</Group>
</Card>
)}

{orderId && (
<Card shadow="sm" padding="lg" radius="md" withBorder>
<Text fw={700} size="lg">
Order ID:
</Text>
<Text mt="xs" c="dimmed">
{orderId}
</Text>
</Card>
)}
</SimpleGrid>

<Box ta="center" mt="xl">
<Text c="dimmed">If you have any questions, feel free to contact us.</Text>
</Box>
</Box>
);
}

主要变化:

  1. 将组件标记为 async
  2. searchParams 类型改为 Promise<{...}>
  3. 在组件内部先 await searchParams 获取参数
  4. 组件返回类型改为 Promise<ReactElement>

如果你的 Next.js 版本低于 14,你也可以考虑升级到最新版本,或者检查你的 next.d.ts 类型定义文件是否有正确的 PageProps 类型定义。

另外,如果你使用的是 Next.js 14 之前的版本,可能需要在 next.config.js 中添加以下配置:

1
2
3
4
5
6
7
8
/** @type {import('next').NextConfig} */
const nextConfig = {
experimental: {
serverActions: true,
},
};

module.exports = nextConfig;