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

使用带回调的useState遇类型错误:Type无调用签名

问题分析与解决方案

错误根源

  1. 组件Props类型声明错误:你把Home组件的类型设为FC<TagProps>,这会让TypeScript认为组件接收的props是TagProps类型,但实际你传入的是setState和state两个与TagProps无关的属性,导致类型完全不匹配。
  2. 组件参数写法错误:函数组件的参数是一个props对象,不能直接将setState和state作为独立参数传入。
  3. tagSpec的key类型不匹配:TagProps中key是string类型,但你定义的是一个函数,导致类型冲突。

分步解决

1. 定义正确的Home组件Props类型

首先为Home组件创建专属的Props接口,明确它需要接收的属性:

import React, { FC, Dispatch, SetStateAction } from 'react';

interface TagProps {
  left: string;
  top: string;
  backgroundColor: string;
  rotation: number;
  label: string;
  key: string;
}

// 定义Home组件的Props类型
interface HomeProps {
  setState: Dispatch<SetStateAction<TagProps[]>>;
  state: TagProps[];
}

2. 修正Home组件的定义

使用正确的Props类型,并通过解构获取setState和state:

const Home: FC<HomeProps> = ({ setState, state }) => {
  const createTag = (e: React.MouseEvent) => {
    // 先计算label和背景色,避免重复调用随机函数
    const label = tech[randomNumber(0, tech.length - 1)];
    const bgColor = randomColour(colors);
    
    const tagSpec: TagProps = {
      left: e.clientX + "px",
      top: e.clientY + "px",
      backgroundColor: bgColor,
      rotation: randomNumber(-20, 20),
      label,
      key: `${label}${bgColor}`, // 改为字符串类型,符合TagProps定义
    };
    setState((prev: TagProps[]) => [...prev, tagSpec]);
  };

  // ... 其他代码
};

3. 可选:补充TagProps的缺失属性

如果需要保留position属性,记得把它添加到TagProps接口中:

interface TagProps {
  left: string;
  top: string;
  backgroundColor: string;
  rotation: number;
  label: string;
  key: string;
  position: string; // 添加该属性
}

关键说明

之前的错误提示2349: This expression is not callable. Type 'Props' has no call signatures,本质是TypeScript错误地将setState推断为TagProps类型(因为你错误地将组件Props设为TagProps),而TagProps不是函数,所以无法调用。修正组件Props类型后,TypeScript就能正确识别setState是状态更新函数,问题自然解决。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 07:24:22