ReactJS路由跳转调用this.props.history.push时报push属性未定义的TypeError错误
Cannot read property 'push' of undefined 排查与解决 核心报错本质
代码执行到 this.props.history.push("/slider") 这行时,this.props.history 本身为 undefined,不存在可调用的 push 方法,因此触发类型错误。结合给出的代码片段,常见触发原因与对应解法如下:
常见踩坑点与修复方式
原因1:类组件未被路由高阶组件包裹,无路由相关props
只有被<Route>直接匹配渲染的组件,才会自动获取React Router注入的history、location、match等路由属性。如果当前组件是路由匹配组件下的深层嵌套子组件、没有被Route直接渲染,就无法通过props拿到history对象。
适配React Router v5及更早版本的解法:使用withRouter高阶组件包裹组件,强制注入路由props。import { withRouter } from 'react-router-dom'; // 原组件逻辑保持不变 class TargetComponent extends React.Component { handleSubmit(e) { e.preventDefault(); this.props.history.push("/slider"); } } // 导出时用withRouter包裹 export default withRouter(TargetComponent);原因2:事件回调的this上下文丢失,无法获取组件props
给出的Button组件直接把this.handleSubmit作为onClick回调,但代码中注释掉了.bind(this)的绑定写法。如果类组件既没有在构造函数里显式绑定方法的this指向,也没有用类属性箭头函数定义方法,那么点击触发回调时,方法内部的this不会指向组件实例,自然无法读取挂载在实例上的props。
两种修复方式二选一即可:- 在构造函数中显式绑定this
constructor(props) { super(props); this.handleSubmit = this.handleSubmit.bind(this); } - 用类属性箭头函数定义方法,自动绑定组件实例上下文
handleSubmit = (e) => { e.preventDefault(); this.props.history.push("/slider"); }
快速区分判断:如果是this绑定丢失的场景,在方法内打印
this.props会直接得到undefined;如果是未注入路由props的场景,this.props存在但内部没有history属性。- 在构造函数中显式绑定this
原因3:React Router v6 版本不兼容旧的props注入逻辑
代码中被注释的const history = useHistory()是React Router v5的hook写法,v6版本已经移除了该API,替换为useNavigate,同时不再自动给类组件注入history相关props。如果项目升级到v6后直接沿用旧的类组件跳转写法,就会报这个错。
v6版本下类组件跳转的兼容解法:写一个自定义高阶组件,在函数组件内通过useNavigate拿到跳转方法,再通过props传给类组件:import { useNavigate } from 'react-router-dom'; // 自定义适配高阶组件 const withNavigate = (WrappedComponent) => { return (props) => { const navigate = useNavigate(); return <WrappedComponent {...props} navigate={navigate} /> } } // 类组件中调用跳转 class TargetComponent extends React.Component { handleSubmit(e) { e.preventDefault(); // v6中原来的history.push方法替换为navigate this.props.navigate("/slider"); } } // 导出时用自定义高阶组件包裹 export default withNavigate(TargetComponent);
快速定位流程
- 在
handleSubmit方法第一行加调试打印:
点击按钮后根据输出判断:console.log('方法上下文this', this, '组件props', this.props)- 如果打印的
this不是当前组件实例:属于this绑定丢失问题,按上述原因2的方案修复 - 如果
this指向组件实例,但props中不存在history/navigate属性:属于路由props未注入问题,按对应版本的适配方案修复
- 如果打印的
- 核对项目安装的React Router版本,匹配对应的路由API写法,避免跨版本混用旧代码逻辑。
内容的提问来源于stack exchange,提问作者tejesh

