‘X’ 不是 React 中的函数 TypeError [已解决]

‘X’ 不是 React 中的函数 TypeError [已解决]

‘X’ is not a function TypeError in React [Solved]

React.js“Uncaught TypeError: X is not a function”发生在我们尝试将不是函数的值作为函数调用时,例如调用 props 对象而不是函数。要解决错误,console.log您正在调用的值并确保它是一个函数。

不是函数反应

下面是错误如何发生的示例。

应用程序.js
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 对象,并且应该访问
setCountprops 上的函数。

应用程序.js
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> ); }

或者,您可以解构函数定义中的道具。

应用程序.js
// 👇️ 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> ); }
React 中出现“Uncaught TypeError: X is not a function”错误的另一个常见原因是当我们尝试对不正确类型的值调用函数时。

例如,如果我们尝试pop()在一个不是数组的值上调用该方法,我们会得到一个错误。

应用程序.js
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.

App.js
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.

App.js
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.