The panel of five judges on the East African country's Constitutional Court said the speaker of parliament acted illegally when she went ahead to allow a vote on the measure.
The ruling was made before a courtroom packed with Ugandans opposing or supporting the measure. Activists erupted in loud cheers after the court ruled the law was "null and void".
Ugandan lawyer Ladislaus Rwakafuuzi, for the activists, said the ruling "upholds the rule of law and constitutionalism in Uganda".
Kosiya Kasibayo, a state attorney, said a decision had not been made on whether to appeal the ruling invalidating the law in the Supreme Court.
The anti-gay measure provided for jail terms of up to life for those convicted of engaging in gay sex. It also allowed lengthy jail terms for those convicted of "attempted homosexuality" or the "promotion of homosexuality".
Although the legislation has wide support in Uganda, it has been condemned in the West as draconian.
The law was passed in December and enacted in February by Ugandan president Yoweri Museveni who said he wanted to deter Western groups from promoting homosexuality among African children.