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

如何解决RTK Query调用TS2554错误并在Firebase创建带图帖子

解决RTK Query Mutation传参错误并实现Firebase帖子创建

错误原因

RTK Query的mutation函数仅支持接收单个参数,你当前的queryFn定义了两个独立参数(post和file),调用时直接传入两个参数违反了这个规则,导致TypeScript抛出Expected 1 arguments, but got 2.ts(2554)错误。

修复步骤

1. 调整RTK Query的Mutation定义

将queryFn的参数改为一个包含post和file的对象,同时更新对应类型:

createPost: builder.mutation({
  // 改为接收单个对象参数
  queryFn: async ({ post, file }: { post: Post; file?: string }) => {
    try {
      const postRef = await addDoc(collection(firestore, 'posts'), post);
      await updateDoc(postRef, { id: postRef.id });

      let imageUrl: string | undefined;
      if (file) {
        const imageRef = ref(storage, `posts/${postRef.id}/image`);
        await uploadString(imageRef, file, 'data_url');

        imageUrl = await getDownloadURL(imageRef);
        await updateDoc(postRef, { imageUrl });
      }

      // 注意:本地post对象不会同步Firestore的更新,直接用imageUrl变量打印最新值
      console.log('imageUrl: ', imageUrl);

      return { data: { postRef, imageUrl } };
    } catch (error: any) {
      return { error: error.message };
    }
  },
  invalidatesTags: ['Post']
}),

2. 修改前端调用代码

将newPost和file包装成一个对象传递给createPost函数:

try {
  // 把两个参数合并为单个对象传入
  await createPost({ post: newPost, file });
} catch (error) {
  console.log({error});
}

额外优化提示

  • 如果需要在创建帖子后获取完整的最新帖子数据,可以在queryFn末尾调用getDoc(postRef)从Firestore拉取更新后的文档,再返回给前端使用。
  • 原代码中post.imageUrl无法获取到Firestore更新后的值,因为本地对象不会自动同步云端修改,直接使用imageUrl变量即可拿到最新的图片地址。

内容的提问来源于stack exchange,提问作者Thiago Souza

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 16:22:29