[SalesForce] error Cannot read property ‘setParams’ of undefined – lightning component

In a lightning component I call an apex method, like that :

for(var cmp in component.find("inQuantity")){
  var CallMethod = component.get("c.calculate")[cmp]; 
  var product = component.get("v.product")[cmp];
  CallMethod.setParams({
    "prod" : JSON.stringify(product)
  });
  vCalcMethod.setCallback(pComponent, function(pResponse) {
    //some code
  });
  $A.enqueueAction(CallMethod);
}

The apex method need a string in parameter, I try to pass it through the setParams. But at this point I got an error in javascript :

Cannot read property 'setParams' of undefined

But when I put a debug console.log('product to string' + JSON.stringify(product )); I got the object into a string, like I want, it is not "undefined".

Best Answer

Your CallMethod variable is undefined. Try changing:

var CallMethod = component.get("c.calculate")[cmp];

to

var CallMethod = component.get("c.calculate");

and make sure you've defined an action called calculate that's accessible on your component.