A spokesman for the Taliban, Qari Mohammad Yousuf, said the group had no hand in the attack. A number of previous suicide attacks on mosques in Afghanistan, including one that killed 30 people last November, have been claimed by a regional affiliate of the Islamic State, an extremist Sunni militia.
The Herat attack followed a terrorist assault Monday on the embassy of Iraq in Kabul in which two assailants were killed after a five-hour gun battle with police.
The embassy had celebrated the recapture of the Iraqi city of Mosul from Islamic State fighters last month. Afterward, there were reports that Islamic State officials warned Shiites in Afghanistan that they would be targeted.
Tuesday's attack, however, was the first such assault on a Shiite mosque in Herat, a gateway to the Afghan border with Iran and a historic center of Shiite faith among the Hazara ethnic community. There has been little history of religious conflict between local Shiites and Sunnis, but the Islamic State has previously stated its intent to divide Afghan Muslim sects.
Abdul Ahad Walizada, a spokesman for the Herat police, described the incident as "a terroristic attack that killed more than 20 of our countrymen while they were praying." He said he did not know the motive. Some witnesses described hearing a second explosion about 10 minutes after the first.
One legislator who arrived soon after the Tuesday bombing at the Javadia mosque, just south of Herat city, described a ghastly scene of bloodied bodies and wounded survivors scattered through the building, where about 300 people had gathered.
After the attack, dozens of angry residents confronted police, complaining that they had failed to intervene while the attack was in progress. There is a police station just 150 feet from the mosque, but the legislator, Mehdi Hadid, said the police were too frightened to take action and remained outside.
A spokesman for the provincial governor, Jalani Farhad, said people pelted the police station with stones and set it on fire.
In the past year, there have been numerous attacks on Shiite places of worship and communities, most claimed by the Islamic State. Last October, during the period of Shiite commemoration known as Ashura, a remote-controlled bomb exploded at a mosque in the northern city of Mazar-e Sharif, killing 17, and gunmen invaded the famous Karte Sakhi shrine in Kabul as it was filled with women and children, killing 10 and wounding many others.
Sayed Salahuddin contributed to this report.