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

React18+Vite中使用mui-tiptap图片上传遇TypeScript错误求助

解决mui-tiptap MenuButtonImageUpload的TypeScript上传错误

错误原因

你的代码中,files.map(async file => ...)返回的是Promise<{src: any; alt: string; title: string;}>组成的数组,但组件要求onUploadFiles的返回值必须是ImageNodeAttributes[](同步数组)或者Promise<ImageNodeAttributes[]>(单个Promise包裹的数组)。你返回的是多个Promise的数组,类型完全不匹配,这就是TypeScript报错的核心原因。

修正代码

用Promise.all将多个Promise合并成一个单独的Promise,这样返回值类型就能符合组件要求:

<MenuButtonImageUpload
  onUploadFiles={(files) => {
    return Promise.all(files.map(async (file) => {
      const formData = new FormData();
      formData.set('file', file);
      const { data } = await axios.post('/api/art', formData, {
        headers: {
          'content-type': 'multipart/form-data'
        }
      });
      // 显式断言src为string,匹配ImageNodeAttributes的类型定义
      return {
        src: data.data.url as string,
        alt: "test",
        title: "test"
      };
    }));
  }}
/>

额外类型优化

如果后端返回的data.data.url类型不确定,建议显式用as string断言类型,或者给axios请求添加响应类型定义,避免TypeScript后续出现隐式类型错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 16:32:06