Ersereum error: Typeerror: x is not a function
As a developer working with intelligent Ethereum contracts, you are probably not a foreign complex world of programming languages and libraries. However, when using certain methods in your Ethereum treaty, you may encounter a mistake that at first glance seems nonsensical. In this article, we dive into specifics of what causes this problem and provide a solution.
Problem: Typeerror: X is not a function
When you try to call the method in your Ethereum contract using contract.methods.Thodname ()
, it provokes a mistake that states that “Xis not a function. This may seem like a general error message, but in fact it is more specifically than that.
Problem: UNBOUND CONSTRUCTOR
In most programming languages, including JavaScript and some other libraries, when you call a method on the object without entering the object itself (ie J. "X), it will look for a constructor’s function defined elsewhere. In this case, however, we are working with a contract, not a class.
Fix: tie the constructor
To solve this problem, you must oblige the constructor of your contractual method to the instance of the contract itself. This is done using the bind method ()
provided by call
.
`Javascript
contract.methods.Method.bind (this) .call ();
`
In this example, we tie the constructor ‘mymethod’ constructor ‘to this' (t.
Proven procedures
To avoid similar problems in the future:
- Make sure your methods are defined as constructors (constructor X ()
) instead of regular functions.
- Use theBind ()
method when calling the contract instance.
By applying these repairs and proven procedures, you should be able to solve Typeerror: X is not an error of the function associated with your Ethereum intelligent contract.
Example code
Here's an example of a code fragment that shows how to solve this problem:
Javascript
Import * as “ether” ethers;
Const MyContract = Artifacts.Require (‘MyContract’);
Contract (‘MyContract’, Async (Accounts) => {
Const Instance = expect mycontract.new ();
Const mymethod = instance.methods.Method;
// Call mymethod without entering x
Console.log (waiting mymethod ()); // output: Typeerror error: x is not a function
// By using Bind () we will solve the problem to enter this problem:
Const Result = expect mymethod.bind (this) .Call ();
Console.log (result);
});
`
Be sure to replace MyContract
The actual name of your contract and edit code accordingly.
Deixe um comentário