Vue3组合式API调用Props函数报Cannot invoke possibly 'undefined'错误如何解决
你遇到的报错本质是Vue组件未标记为required: true的Props,默认会被TypeScript推导为可选类型,你定义的sortSearch没有设置必填标识,TS就会认为它可能为undefined,直接调用就会抛出Cannot invoke an object which is possibly 'undefined'错误。
可根据你的业务场景选择以下任意一种解决方案:
- 方案1:调用时使用可选链操作符(推荐用于回调为可选参数的场景)
不需要修改Props定义,调用时直接用?.操作符,函数存在时才会执行,不存在也不会触发运行时报错:
props.sortSearch?.(s, state.currentSortDir);
- 方案2:将Props标记为必填(推荐用于父组件必须传入该回调的场景)
给sortSearch加上required: true标识,告诉TypeScript这个参数一定会传入,不存在undefined的情况:
export default defineComponent({ props: { sortSearch: { type: Function as PropType<SortSearchInterface>, required: true } } })
- 方案3:调用时使用非空断言(适用于你百分百确定父组件一定会传该参数的场景)
不需要修改Props定义,调用时加!告诉TS这个值肯定不是undefined:
props.sortSearch!(s, state.currentSortDir);
注意:如果实际运行时父组件没有传该参数,会触发运行时报错。
- 方案4:给Props设置默认空函数
给sortSearch设置默认值为无操作的空函数,保证不管有没有传参,调用的都是可执行的函数:
export default defineComponent({ props: { sortSearch: { type: Function as PropType<SortSearchInterface>, default: () => () => {} } } })
内容的提问来源于stack exchange,提问作者V H
相关产品推荐
相关产品推荐

