‘X’ 不是 React 中的函数 TypeError [已解决]
‘X’ is not a function TypeError in React [Solved]
React.js“Uncaught TypeError: X is not a function”发生在我们尝试将不是函数的值作为函数调用时,例如调用 props 对象而不是函数。要解决错误,console.log
您正在调用的值并确保它是一个函数。
下面是错误如何发生的示例。
import {useState} from 'react'; // 👇️ should take props object and not setCount directly // ⛔️ Uncaught TypeError: setCount is not a function function Child(setCount) { return ( <div> <button onClick={() => setCount(current => current + 1)}> Click </button> </div> ); } export default function App() { const [count, setCount] = useState(0); return ( <div> <Child setCount={setCount} /> <h2>Count: {count}</h2> </div> ); }
Child
组件应该获取props
对象,但我们将其命名为
并setCount
尝试调用组件中的 props 对象。
setCount
中的值Child
并确保它是一个函数。该Child
组件应该接受一个 props 对象,并且应该访问
setCount
props 上的函数。
import {useState} from 'react'; // 👇️ now component takes props object // and calls function as props.setCount function Child(props) { console.log('props obj:', props); return ( <div> <button onClick={() => props.setCount(current => current + 1)}> Click </button> </div> ); } export default function App() { const [count, setCount] = useState(0); return ( <div> <Child setCount={setCount} /> <h2>Count: {count}</h2> </div> ); }
或者,您可以解构函数定义中的道具。
// 👇️ destructure the setCount prop // and use it directly function Child({setCount}) { return ( <div> <button onClick={() => setCount(current => current + 1)}>Click</button> </div> ); } export default function App() { const [count, setCount] = useState(0); return ( <div> <Child setCount={setCount} /> <h2>Count: {count}</h2> </div> ); }
例如,如果我们尝试pop()
在一个不是数组的值上调用该方法,我们会得到一个错误。
const obj = {}; // ⛔️ Uncaught TypeError: obj.pop is not a function obj.pop();
该pop()
方法只能在数组上调用,因此尝试在任何其他类型上调用它会抛出“X 不是函数”错误,因为该pop
类型上不存在该函数。
The best way to debug this is to console.log
the value you are calling the
function on and make sure it is of the correct type.
const obj = {}; console.log(typeof obj); // 👉️ "object" console.log(Array.isArray(obj)); // 👉️ false
Once you make sure the value you are calling the method on is of the expected
type and that the method is supported by said type, the error will be resolved.
You can also use a conditional to check if the value is of the correct type
before calling the method.
const obj = {}; if (Array.isArray(obj)) { console.log(obj.pop()); }
Conclusion #
The React.js “Uncaught TypeError: X is not a function” occurs when we try to
call a value that is not a function as a function, e.g. calling the props object
instead of a function. To solve the error, console.log
the value you are
calling and make sure it is a function.