React Router v7.5.3导航报错:TypeError: 无法读取undefined的toUpperCase属性
我在React项目中使用react-router实现导航,代码在v7.4.0版本运行正常,但升级到v7.5.3后,调用navigate函数时触发以下错误:
TypeError: Cannot read properties of undefined (reading 'toUpperCase') 9 | const handleNavigation = () => { 10 | console.log("button click"); > 11 | navigate('/about/nested'); | ^ 12 | }; 13 | 14 | return ( at isMutationMethod (node_modules/react-router/dist/development/index.js:4699:42) at getDataStrategyMatchLazyPromises (node_modules/react-router/dist/development/index.js:4101:5) at getDataStrategyMatch (node_modules/react-router/dist/development/index.js:4114:23) at node_modules/react-router/dist/development/index.js:3605:14 at Array.map (<anonymous>) at getMatchesToLoad (node_modules/react-router/dist/development/index.js:3586:27) at handleLoaders (node_modules/react-router/dist/development/index.js:1804:47) at startNavigation (node_modules/react-router/dist/development/index.js:1611:15) at Object.navigate (node_modules/react-router/dist/development/index.js:1473:11) at node_modules/react-router/dist/development/index.js:5497:22
简化后的代码示例
import { render, screen, fireEvent } from '@testing-library/react'; import { createMemoryRouter, Outlet, RouterProvider } from 'react-router'; import React, { act } from 'react'; import { useNavigate } from 'react-router'; const MyComponent = () => { const navigate = useNavigate(); const handleNavigation = () => { console.log("button click"); navigate('/about/nested'); }; return ( <div> <button onClick={handleNavigation}>Go to Nested</button> <Outlet /> </div> ); }; const NestedComponent = () => { return <div>Nested Component</div>; }; test('navigates to nested route correctly', async () => { const routes = [ { path: '/', element: <MyComponent />, children: [ { path: 'about/nested', element: <NestedComponent /> }, ], }, ]; const router = createMemoryRouter(routes, { initialEntries: ['/'], }); render( <RouterProvider router={router} /> ); // Simulate button click to navigate await act(async () => { fireEvent.click(screen.getByText(/Go to Nested/i)); }); // Assert the expected outcome expect(await screen.findByText(/Nested Component/i)).toBeInTheDocument(); });
解决方案与见解
这个错误是React Router v7.5.x版本引入的内部bug,在isMutationMethod函数中尝试对一个未定义的值调用toUpperCase导致的。目前社区已有不少开发者反馈类似问题,主要集中在v7.5.1到v7.5.3版本中。
可以尝试以下几种解决方式:
- 临时降级版本:将react-router和react-router-dom降级到v7.4.0或v7.5.0,这两个版本未引入该问题,能恢复正常功能。
- 等待官方修复:React Router团队已经关注到这个问题,后续版本会推出修复补丁,可留意官方更新日志。
- 检查路由配置:虽然你的配置在旧版本正常,但可以尝试将子路由的
path改为相对路径(确保导航路径和路由配置匹配),或者显式指定完整路径,不过这并非根本解决办法,仅作为临时排查手段。
内容的提问来源于stack exchange,提问作者NAVEED
相关产品推荐
相关产品推荐

